Skip to content
Strings and Characters
step 1/5

Reading — step 1 of 5

Learn

~2 min readHash Tables, Vectors, Strings

Strings in Common Lisp are vectors of characters. Most vector ops work; plus a string-specific library.

Strings

"hello world"
(length "hello")           ; 5
(char "hello" 0)            ; #\h
(string-upcase "hello")     ; "HELLO"
(string-downcase "HI")      ; "hi"
(subseq "hello world" 6)    ; "world"
(subseq "hello" 1 4)        ; "ell"

Concatenation

(concatenate 'string "hello" " " "world")    ; "hello world"
(format nil "~a ~a" "hello" "world")          ; "hello world"

There's no + or .. for strings. concatenate works on any sequence (including vectors, lists).

Splitting

No built-in split. Use library cl-ppcre (regex) or write your own:

(defun split (s delim)
    (loop for i = 0 then (1+ pos)
          for pos = (position delim s :start i)
          collect (subseq s i (or pos (length s)))
          while pos))

(split "a,b,c,d" #\,)        ; ("a" "b" "c" "d")

Comparison

  • string= — case sensitive, equal
  • string-equal — case insensitive, equal
  • string<, string>, string<=, string>= — lexicographic
  • string/= — not equal
(string= "abc" "abc")        ; t
(string-equal "ABC" "abc")    ; t
(string< "abc" "abd")         ; 2 (mismatch position) or t

Searching

(search "world" "hello world")       ; 6 (position)
(position #\o "hello")                ; 4
(count #\l "hello")                   ; 2

Characters

Literals: #\a, #\Space, #\Newline, #\Tab, #\A.

(char-code #\A)              ; 65
(code-char 97)                ; #\a
(char-upcase #\a)             ; #\A
(alpha-char-p #\a)            ; t
(digit-char-p #\7)            ; 7 (returns the digit value)

Format for building strings

(format nil "~a is ~a" "Ada" 36)              ; "Ada is 36"
(format nil "~{~a~^, ~}" '(1 2 3))             ; "1, 2, 3"

Beyond ASCII

Common Lisp implementations vary in Unicode support. SBCL has full Unicode strings. For heavy text processing, also look at babel (encoding conversions) and cl-unicode (full UCD tables).

Strings as sequences

Most sequence functions work on strings:

(map 'string #'char-upcase "hello")           ; "HELLO"
(remove #\l "hello")                            ; "heo"
(sort "hello" #'char<)                          ; "ehllo" (sorted chars)

The 'string is the result type — map returns the requested sequence type.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…