s c h e m a t i c s : c o o k b o o k

/ StringRecipes / Cookbook.StringReverse

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Reversing a String by Words or Characters

Problem

You want to reverse the words or characters in a string

Solution

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,"

Discussion

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

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
Other Parents:
Next Topic: StringTabs

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest