s c h e m e w i k i . o r g

/ StringRecipes? / Sandbox.StringBasics

This Web


All Webs



Schematics Home
TWiki Shorthand

Offsite Links

Lambda the Ultimate

String Basics

In Scheme, literal strings are enclosed in quotes. According to R5RS, "A string constant may continue from one line to the next, but the exact contents of such a string are unspecified.", probably to account for platform differences in handling newlines. The PLT and mzScheme interpreters allow you to write string literals with linebreaks inline, i.e.
>(define a-string "A literal string with a linebreak (\"\\n\")
in it")
"A literal string with a linebreak (\"\\n\")\nin it"
>(display a-string)
A literal string with a linebreak ("\n")
in it
R5RS provides the string->list and list->string functions to convert between strings and lists:
> (string->list "Hello")
(#\H #\e #\l #\l #\o)
> (list->string '(#\S #\c #\h #\e #\m #\e))
If you want to find out what character is at a specific position in a string, use (string-ref string *i*), where i is a 0-based index in the string:
>(string-ref a-string 0)
string-length will tell you how long a string is.
> (string-length a-string)
You may have heard that Scheme provides mutable strings. If you want to modify a string in place, the string-set! function will do that for you. However, if you gave the string as a literal to the REPL, string-set! will give you a surprise:
> (string-set! a-string 0 #\1)
string-set!: expects type <mutable-string> as 1st argument, given: "A literal string with a linebreak (\"\\n\")\r\nin it"; other arguments were: 0 #\1
You can make a copy of a string using string-copy. This will yield a mutable string:
> (define a-copy (string-copy a-string))
> (string-set! a-copy 0 #\1)
> a-copy
"1 literal string with a linebreak (\"\\n\")\r\nin it"
You can allocate a new string with make-string. make-string comes in 2 forms, the second allows you to specify an initial character:
> (make-string 5)
> (make-string 5 #\*)
You can also use string-append to join strings. This
> (string-append "Hello" ", " "Scheme" "!")
"Hello, Scheme!"
R5RS provides a number of useful string functions, but you should also be aware of SRFI 13 (String Library) and SRFI-14 (Character Set Library), which add a number of very useful functions.

-- GordonWeakliem - 05 Apr 2004

© 2004 by the contributing authors. / You are Main.guest