Friday, September 29, 2006

Lisp - Strings and Characters

Lisp has an ackward syntax for characters.
In Lisp string is a array of characters. According to HyperSpec'd defination of String

" A string is a specialized vector whose elements are of type character or a subtype of type character. When used as a type specifier for object creation, string means (vector character)."

The simple example of Lisp string are
"hello lisp"
"this post is about lisp strings and characters"

Now lets see some of the string functions
1) string-concat
This function as expected concates all the strings passes as arguments
(string-concat)
""
(string-concat "Hello")
"Hello"
(string-concat "Hello" " ")
"Hello "
(string-concat "Hello" " " "World")
"Hello World"

2)subseq
This function is general function for any kind of sequences, like list, arrays
(subseq "Hello" 2 4)
"ll"

3)stringp
This function checks if given argument is string or not
(stringp "hello")
T
(stringp '(1 2 3))
NIL

4) string-equal is a function which compares two strings with case ignored.
(string-equal "hello" "Hello")
T

(string-equal "hello" "hel")
NIL

5)reverse works on any sequnce
(reverse '(1 2 3))
(3 2 1)

(reverse "hello")
"olleh"



Characters forms string
Lets see the 3rd charcter of string "hello"
(char "hello" 3)
#\l

1) Actually each charcter is associated with a number, one can find that number by
using function char-code

(char-code #\a)
97
In this case the character code returned is ASCII, but it is code use by implementation.
(char-int #\a)
97

2) digit-char-p checks if a character passed as argument is digit or not
(digit-char-p #\a)
NIL
(digit-char-p #\9)
9
(digit-char-pa #\1)
1

4)code-char returns a character for given code
(code-char 123)
#\{

5) Some special chracters
#\Tab
#\Newline
#\Space

All of above are case-insensitive


clisp supports unicode and using function code-char one can easily get
representation of any code.

3 comments:

ThePriselive said...

Thank you so much for the post. Very helpful indeed. Looking forward to more of such useful and informative posts. thepriselive

ThePriselive said...

Hey what a nice post you have and I really agree with you!
thepriselive

Indian Wedding Menswear said...

See your article updates, always naturally excited . The content of your article is wonderful , classic , humorous . To bring people a lot of happiness . Not only that, it also contains a lot of meaningful knowledge and helpful information . Anarkali suits