Strings
So far we've learnt about the following types of Lisp object:
- Numbers, like 2, 4, and 17.
- Procedure names, like + and list
- Lists, like (1 2 3 4) and (+ 3 6).
We also learnt that Lisp uses lists for both data and programs. The first list (1 2 3 4) is data, because 1 isn't the name of a procedure. The second list, (+ 3 6), is a procedure call to add 3 and 6 (or it could be data that just happens to look like that procedure call).
Strings
The new type is a string: a sequence of any characters enclosed in double-quotes. So here are four strings:
"cat"
"dog"
"Once upon a time there was a prince"
""
The last one is the empty string, which contains no characters, but its still a valid and useful string. You can include a double-quote in a string by prefixing it with a backslash:
"He shouted \"Help!\" and ran away."
Now some procedures that work with strings (note that most of these also work with lists):
Finding the length of a string: length
We've already met length with lists. It can also be used to find the length of a string; for example:
CL-USER > (length "Lisp")
4
Reversing a string: reverse
The procedure reverse also works for strings:
CL-USER > (reverse "dog")
"god"
Joining two (or more) strings together: concatenate
The second argument has to be 'string to tell the procedure what type of thing you're concatenating:
CL-USER > (concatenate 'string "band" "age") "bandage"
The concatenate procedure can take an arbitrary number of strings and they will all be joined into one long string.
Getting a subsequence from a string: subseq
This procedure extracts part of a string. It takes three parameters:
- the string
- the number of the first character you want
- the number of the character one after the last character you want
The characters are counted starting at 0. For example:
CL-USER > (subseq "averylongword" 5 9)
"long"
If you leave out the third parameter you get the rest of the string to the end.
Writing a procedure using strings
Now we're ready to write a procedure using strings. Let's write a simple piglatin program. It takes the first letter of the word, concatenates it to the word with the first letter removed, and adds "ay" on the end:
(defun piglatin (word)
(concatenate 'string (subseq word 1) (subseq word 0 1) "ay"))
Try it out:
CL-USER 16 : 2 > (piglatin "pig")
"igpay"
Note that it doesn't work perfectly. Try:
(piglatin "ant")
Later you'll learn about the if construct that will enable you to make a piglatin function that works perfectly.
Exercises
1. Reverse the middle letters of a word
Write a procedure midverse to reverse all but the first and last letters of a word. For example:
(midverse "retinues")
becomes "reunites". Check that
(midverse (midverse word))
leaves the word unchanged.
2. Rotate a string n places to the left
Write a procedure rotate that rotates a string n characters to the left. So, for example:
(rotate "mousetrap" 5)
should give:
"trapmouse"
blog comments powered by Disqus