Lisp - Accessing Characters of String



In Lisp, a String is an array of characters. We can access characters of strings using multiple ways−

  • char method. It takes two argument, a string and and index and returns the corresponding character.

  • schar method. schar method is similar to char method. It is for simple strings and is generally faster. It takes two argument, a string and and index and returns the corresponding character.

  • aref method. It takes two argument, a string as array and and index and returns the corresponding character.

Index starts from 0. As above methods returns characters, returned value is represented with #\.

Example - Using char function to access characters

char method takes two argument, a string and and index and returns the corresponding character.

Create the source code file named main.lisp and type the following code in it.

main.lisp

; define a parameter test-string
(defparameter test-string "TutorialsPoint.com")

; access character at index 5 and print
(write(char test-string 5))

; terminate printing
(terpri)

; access character at index 12 and print
(write(char test-string 12))

Output

When you execute the code, it returns the following result −

#\i
#\n

Example - Using schar function to access characters

schar method takes two argument, a string and and index and returns the corresponding character.

Update source code file named main.lisp and type the following code in it.

main.lisp

; define a parameter test-string
(defparameter test-string "TutorialsPoint.com")

; access character at index 5 and print
(write(schar test-string 5))

; terminate printing
(terpri)

; access character at index 12 and print
(write(schar test-string 12))

Output

When you execute the code, it returns the following result −

#\i
#\n

Example - Using aref function to access characters

aref method takes two argument, a string as array and and index and returns the corresponding character.

Update source code file named main.lisp and type the following code in it.

main.lisp

; define a parameter test-string
(defparameter test-string "TutorialsPoint.com")

; access character at index 5 and print
(write(aref test-string 5))

; terminate printing
(terpri)

; access character at index 12 and print
(write(aref test-string 12))

Output

When you execute the code, it returns the following result −

#\i
#\n
Advertisements