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

/ StringChapter / Cookbook.StringFilterCharSet

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

Filtering a String for a Set of Characters

Problem

You want to remove all but a specified set of characters from a string.

Solution

This is really a extension of what we talked about in StringCheckForChar. SRFI-13 provides string-filter and string-delete functions, which are inverse operations:
> (require (lib "string.ss" "srfi" "13"))
> (string-filter char-set:letter "Hello, World!")
"HelloWorld"
> (string-delete char-set:letter "Hello, World!")
", !"

Discussion

The first thing to note is that the SRFI-13 implementation that ships with PLT, as well as the one provided by Schematics, differ from the spec in that they swap the order of the 1st two arguments. This can be a little confusing. Second, both functions allow you to specify the filter argument in 3 ways: as a character, a char-set, or a predicate. For example, the following 3 are equivalent methods of stripping a hyphen from a string:
(string-delete (char-set #\-) "555-1212")
(string-delete #\- "555-1212")
(string-delete (lambda (c) (eq? #\- c)) "555-1212")

It's useful to be able to define a function make-filter which returns a function with arguments partially bound.

(define (make-filter condition)
    (lambda (str)
      (string-filter condition str)))
Once you've defined this, you can call the result directly, or give it a better name:
> ((make-filter char-set:digit) "555-1212")
"5551212"
> (define (digits-only str)
  ((make-filter char-set:digit) str))
> (digits-only "555-1212")
"5551212"

-- GordonWeakliem - 19 Apr 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 180

 
 
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