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

/ StringRecipes / Cookbook.StringCheckForChar

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

Checking a String for a Character

Problem

You need to find out if a string contains a character. You probably want to know the index of where the character was found.

Solution

This isn't built into R5RS, but is built into SRFI-13, in the form of string-index and string-index-right. string-index can look for a character, a char-set (see SRFI-14), or can be controlled by a predicate. So if you want to find the comma in the string "Hello, World!", the following 3 forms are equivalent:
(require (lib "string.ss" "srfi" "13")
           (lib "char-set.ss" "srfi" "14"))
> (string-index "Hello, World!" #\,)
5
> (string-index "Hello, World!" (char-set #\,))
5
> (string-index "Hello, World!" (lambda (c) (eq? c #\,)))
5

string-index returns #f if no match is found:

> (string-index "Hello, World!" #\?)
#f

Discussion

SRFI-14's char-set is pretty cool in its own right. Let's say you want to find all the punctuation in the same string; the following returns a list of the indices where any puctuation is found:
> (let loop ((next-index (string-index "Hello, World!" char-set:punctuation 0))
           (result '()))
  (if (not next-index)
      result
      (loop (string-index "Hello, World!" 
                          char-set:punctuation 
                          (+ 1 next-index)) 
            (cons next-index result))))
(12 5)

-- GordonWeakliem - 09 Apr 2004

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

 
 
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