Chuyển đến nội dung

Bài 8 · Syntax and Evaluation

Characters and Strings

Work with characters and strings in Common Lisp: literals, subseq, concatenate, search, comparison, case conversion, and the powerful format directives.

Text in Common Lisp is built from two types: characters (single letters, digits and symbols) and strings (one-dimensional arrays of characters). Because a string is a vector, every sequence function you learn later (length, subseq, reverse, position) works on strings as well. This lesson covers the string-specific functions, comparisons, and the format function that Lisp programmers use for almost all text building.

Characters

A character literal starts with #\:

LISP
#\a            ; the letter a
#\A            ; the letter A (case is preserved in characters)
#\Space        ; named characters
#\Newline
#\Tab
(char-code #\A)        ; => 65
(code-char 97)         ; => #\a
(char-upcase #\a)      ; => #\A
(char-downcase #\Q)    ; => #\q
(alpha-char-p #\a)     ; => T
(digit-char-p #\7)     ; => 7   (the digit's weight, or NIL)
(upper-case-p #\a)     ; => NIL
(char= #\a #\a)        ; => T
(char< #\a #\b)        ; => T

Use char= for comparing characters, or char-equal to ignore case.

Strings

String literals use double quotes. Only two characters are special inside: \" (a quote) and \\ (a backslash). \n is not a newline in Lisp; the backslash just escapes the next character, so "a\nb" is the string anb.

LISP
"hello"
"She said \"hi\""        ; contains double quotes
(length "hello")         ; => 5
(char "hello" 1)         ; => #\e     (0-based index)
(aref "hello" 0)         ; => #\h     (char works for strings, aref for any array)
(subseq "hello world" 6)       ; => "world"
(subseq "hello world" 0 5)     ; => "hello"   end index is exclusive
(reverse "abc")          ; => "cba"
(string #\a)             ; => "a"
(make-string 3 :initial-element #\x)  ; => "xxx"

To put a newline inside a string, use the ~% format directive, or insert the character itself:

LISP
(format nil "line one~%line two")
(format nil "a~Ab" #\Newline)   ; a, a real newline, then b

Literal strings are constants

Do not modify a string literal in place; the effect is undefined (SBCL may signal an error). Make a copy first:

LISP
(let ((s (copy-seq "hello")))
  (setf (char s 0) #\J)
  s)                     ; => "Jello"

Building strings

LISP
(concatenate 'string "foo" "bar" "baz")   ; => "foobarbaz"
(format nil "~a-~a" "x" "y")              ; => "x-y"
(princ-to-string 3.5)                     ; => "3.5"
(write-to-string '(1 2 3))                ; => "(1 2 3)"
(string-upcase "hello")                   ; => "HELLO"
(string-downcase "HeLLo")                 ; => "hello"
(string-capitalize "hello wide world")    ; => "Hello Wide World"
(string-trim " " "  padded  ")            ; => "padded"
(string-left-trim "0" "00042")            ; => "42"

To build a string piece by piece, with-output-to-string gives you a stream:

LISP
(with-output-to-string (out)
  (dotimes (i 3)
    (format out "item ~a~%" i)))
;; => "item 0
;; item 1
;; item 2
;; "

Comparing and searching

LISP
(string= "abc" "abc")      ; => T         case-sensitive
(string-equal "abc" "ABC") ; => T         case-insensitive
(string< "apple" "banana") ; => 0         true: returns the mismatch index (a true value)
(string> "apple" "banana") ; => NIL
(search "lo" "hello")      ; => 3         index where the substring starts
(search "xyz" "hello")     ; => NIL
(position #\l "hello")     ; => 2         first match
(position #\l "hello" :from-end t)  ; => 3
(count #\l "hello")        ; => 2
(find #\z "hello")         ; => NIL
(substitute #\- #\Space "a b c")  ; => "a-b-c"
(remove #\l "hello")       ; => "heo"
(every #'alpha-char-p "abc")      ; => T

Never compare strings with eq or eql: they compare identity, not content. Use string= or equal.

LISP
(eq "a" "a")        ; => NIL (probably)
(equal "a" "a")     ; => T

Converting

LISP
(parse-integer "123")             ; => 123
(parse-integer "12x" :junk-allowed t) ; => 12
(coerce "abc" 'list)              ; => (#\a #\b #\c)
(coerce '(#\h #\i) 'string)       ; => "hi"
(read-from-string "(1 2 3)")      ; => (1 2 3)   ; careful with untrusted input!

There is no standard split or join; the standard library predates them. Programmers write a small helper, or use a library such as cl-ppcre or str (see the tooling chapter). The stand-in below shows the classic helper written in the style Lisp uses (find with position, take pieces with subseq).

format directives

format is a tiny language. Everything between ~ and a letter is a directive.

Directive Meaning Example
~a Print like princ (for humans) (format nil "~a" "hi") => "hi"
~s Print like prin1 (readable) (format nil "~s" "hi") => "\"hi\""
~d Decimal integer (format nil "~5d" 42) => " 42"
~f Fixed float (format nil "~,2f" 3.14159) => "3.14"
~b ~o ~x Binary, octal, hex (format nil "~b" 5) => "101"
~% Newline
~& Newline only if not already at line start
~{ ... ~} Loop over a list see below
~^ Exit a loop at the last item
~:d Digit grouping (format nil "~:d" 1234567) => "1,234,567"
~r English words (format nil "~r" 3) => "three"
LISP
(format nil "~{~a~^, ~}" '(1 2 3))   ; => "1, 2, 3"
(format t "Name: ~10a|~%" "Ada")     ; pads to 10 columns:  Name: Ada       |
(format t "~a is ~a years old~%" "Bo" 7)

Use ~a for display and ~s when you want output Lisp could read back.

Stand-in: splitting and joining strings

This is JavaScript written the way a Common Lisp programmer would write a split helper, with explicit search and slicing. It is a stand-in (not Lisp) that shows the algorithm, plus a tiny format that understands ~a, ~s and ~%.

JS Stand-in: split, join and mini format

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Strings are vectors

Since a string is a vector of characters, sequence functions apply directly: map, reduce, remove-if, sort (on a copy), and loop ... across.

LISP
(map 'string #'char-upcase "shout")        ; => "SHOUT"
(remove-if-not #'alpha-char-p "a1b2c3")    ; => "abc"
(sort (copy-seq "banana") #'char<)         ; => "aaabnn"
(loop for c across "hello" count (find c "aeiou"))  ; => 2

More on sequences in Vectors and Sequences.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does (subseq "hello world" 0 5) return?

    subseq takes a start index (inclusive) and end index (exclusive), so indices 0 to 4 give hello.
  2. 2. How do you compare two strings for equal content, ignoring case?

    string-equal ignores case; string= is case-sensitive; eq compares identity.
  3. 3. What is "a\nb" in Common Lisp?

    Inside a Lisp string a backslash only escapes the next character, so \n is just n. Use ~% or #\Newline.
  4. 4. What does (format nil "~{~a~^, ~}" '(1 2 3)) produce?

    ~{ ~} loops over the list and ~^ stops the separator after the last item; nil as destination returns a string.

Summary

  • Characters are written #\a; strings are vectors of characters in double quotes.
  • Use subseq, concatenate 'string, search, position, string-upcase, string-trim for everyday work.
  • string= compares content (case-sensitive); string-equal ignores case; never use eq.
  • Do not modify string literals; copy them first.
  • format builds and prints text with directives such as ~a, ~s, ~d, ~f, ~{ ~}.
  • There is no built-in split or join: write a helper or use a library.

Next: Conditionals and Equality

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.