Skip to main content

char, schar

char, schar Accessor

Syntax:

char string index → character

schar string index → character

(setf (char string index**)** new-character**)**

(setf (schar string index**)** new-character**)**

Arguments and Values:

string—for char, a string; for schar, a simple string.

index—a valid array index for the string.

character, new-character—a character .

Description:

char and schar access the element of string specified by index.

char ignores fill pointers when accessing elements.

Examples:

(setq my-simple-string (make-string 6 :initial-element #\A))"AAAAAA" 
(schar my-simple-string 4) → #\A
(setf (schar my-simple-string 4) #\B) → #\B
my-simple-string → "AAAABA"
(setq my-filled-string
(make-array 6 :element-type ’character
:fill-pointer 5
:initial-contents my-simple-string))
"AAAAB"
(char my-filled-string 4) → #\B
(char my-filled-string 5) → #\A
(setf (char my-filled-string 3) #\C) → #\C
(setf (char my-filled-string 5) #\D) → #\D
(setf (fill-pointer my-filled-string) 6)6
my-filled-string → "AAACBD"


See Also:

aref, elt, Section 3.2.1 (Compiler Terminology)

Notes:

(char s j) (aref (the string s) j)

Expanded Reference: char, schar

Basic character access with char

char accesses the character at a given zero-based index in a string.

(char "Hello" 0)
=> #\H

(char "Hello" 4)
=> #\o

Using schar for simple strings

schar works like char but is restricted to simple strings (no fill pointers, not displaced, not adjustable). It may be more efficient.

(schar "Common Lisp" 0)
=> #\C

(schar "Common Lisp" 7)
=> #\L

Modifying characters with setf

Both char and schar are setf-able, allowing in-place modification of string characters.

(let ((s (copy-seq "hello")))
(setf (char s 0) #\H)
s)
=> "Hello"

(let ((s (make-string 5 :initial-element #\a)))
(setf (schar s 2) #\X)
s)
=> "aaXaa"

char ignores fill pointers when accessing elements

char can access elements beyond the fill pointer, while functions like elt respect the fill pointer.

(let ((s (make-array 6 :element-type 'character
:fill-pointer 3
:initial-contents "abcdef")))
(list (char s 4) ; accesses beyond fill pointer
(length s))) ; length respects fill pointer
=> (#\e 3)

char is equivalent to aref on strings

(char s i) is equivalent to (aref (the string s) i).

(let ((s "abcdef"))
(list (char s 2) (aref s 2) (eql (char s 2) (aref s 2))))
=> (#\c #\c T)