e r l a n g : c o o k b o o k

/ Erlang.StringCheckForChar

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

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

Use the string library string:chr and string:rchr functions. string:chr searches a string for a character (starting from the left hand side of the string), and returns its index. string;rchr performs the same task, starting from the right hand side. Note that all Erlang indexes are 1-based:
1> string:chr("Hello, World!", $,).
6
2> string:chr("My, this is a lot of commas, I guess.", $,).
3
3> string:rchr("My, this is a lot of commas, I guess.", $,).
28
string:chr and string:rchr return 0 if no match is found:
4> string:chr("This sentence has no commas.", $,).
0
5> string:rchr("This sentence has no commas.", $,).
0

Discussion

Contributors

Based on work by GordonWeakliem and NoelWelsh.

-- BrentAFulgham - 21 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 170

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
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