Nick Welki
Nick Welki

Reputation: 455

Split string into individual characters

I am having two problems while working in Lisp and I can't find any tutorials or sites that explain this. How do you split up a string into its individual characters? And how would I be able to change those characters into their corresponding ASCII values? If anyone knows any sites or tutorial videos explaining these, they would be greatly appreciated.

Upvotes: 5

Views: 4906

Answers (4)

Rainer Joswig
Rainer Joswig

Reputation: 139251

CL-USER 87 > (coerce "abc" 'list)
(#\a #\b #\c)


CL-USER 88 > (map 'list #'char-code "abc")
(97 98 99)

Get the Common Lisp Quick Reference.

Upvotes: 11

Rörd
Rörd

Reputation: 6681

A Lisp string is already split into its characters, in a way. It is a vector of characters, and depending upon what you need to do, you can use either whole string operations on it, or any operations applicable to vectors (like all the operations of the sequence protocol) to handle the individual characters.

Upvotes: 1

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17773

You can also use elt or aref to get specific characters out of a string.

One of the best sites for an in-depth introduction to Common Lisp is the site for the Practical Common Lisp book (link to the section on numbers, chars and strings). The whole book is available online for free. Check it out.

Upvotes: 0

edgarmtze
edgarmtze

Reputation: 25038

split-string splits string into substrings based on the regular expression separators Each match for separators defines a splitting point; the substrings between splitting points are made into a list, which is returned. If omit-nulls is nil (or omitted), the result contains null strings whenever there are two consecutive matches for separators, or a match is adjacent to the beginning or end of string. If omit-nulls is t, these null strings are omitted from the result. If separators is nil (or omitted), the default is the value of split-string-default-separators.

As a special case, when separators is nil (or omitted), null strings are always omitted from the result. Thus:

(split-string " two words ") -> ("two" "words")
The result is not ("" "two" "words" ""), which would rarely be useful. If you need
such a result, use an explicit value for separators:
(split-string " two words " split-string-default-separators)  -> ("" "two" "words" "")

More examples:
(split-string "Soup is good food" "o")   ->   ("S" "up is g" "" "d f" "" "d")
(split-string "Soup is good food" "o" t) -> ("S" "up is g" "d f" "d")
(split-string "Soup is good food" "o+")  ->  ("S" "up is g" "d f" "d")

Upvotes: 0

Related Questions