You want to reverse the words or characters in a string
Wait, don't tell me, it's...
SRFI-13!
string-reverse will reverse the characters of a string, and
string-reverse! will do the same, in place.
> (require (lib "string.ss" "srfi" "13"))
> (string-reverse "Hello, World!")
"!dlroW ,olleH"
Reversing a string by words is a combination of list and string operations:
> (string-join (reverse (string-tokenize "Hello, World!")) " ")
"World! Hello,"
string-reverse is standard CS 101 stuff, so there's not much to discuss there. The 2nd recipe is a bit more interesting. This works by reversing the output of
string-tokenize, then joining the list back into a single string, delimiting each word with a space. The way
string-tokenize works is to collect tokens composed of the characters you want to keep (by default,
char-set:graphic), terminating a token at the first occurrence of any character not in the set, and discarding any characters not in the set.
char-set:graphic gives you a pretty lenient definition of "word". Let's say you had a more stringent definition, where "word" means alphanumeric characters.
> (string-join (reverse (string-tokenize "Hello, World!" char-set:letter+digit)) " ")
"World Hello"
This conforms to a more sensible definition of word, but has discarded the punctuation.
string-concatenate-reverse is another interesting function from
SRFI-13. It works like a combination of
string-join and
reverse, but without specifying a delimiter string:
> (string-concatenate-reverse (string-tokenize "Hello, World!"))
"World!Hello,"
--
GordonWeakliem - 20 Apr 2004