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

/ Erlang.StringSubstring

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

Accessing Substrings

Problem

You want to extract part of a string.

Solution

Option 1: Generic Lists Module

The lists:sublist function is the most general solution. lists:sublist has two forms: (a) the first takes a string and a number of entries to return, and (b) a version that takes a string, a start index (indexed from 1), and an end index. For example:
1> lists:sublist("Hello, World!", 7).
"Hello, "
2> lists:sublist("Hello, World!", 1, 5).
"Hello"
3> lists:sublist("Hello, World!", 8, 12).
"World"
lists:sublist always allocates a new string.

Option 2: String Module

There is also a string module, which contains many more string-specific functions. To take the substring of a string, use the string:substr function. This function has two forms: (a) the first takes a string and a start index (indexed from 1), and (b) a version that takes a string, a start index (indexed from 1), and an end index. For example:
1> string:substr("Hello, World!", 8).
"World!"
2> string:substr("Hello, World!", 1, 5)
"Hello"
3> string:substr("Hello, World!", 8, 12)
"World!"
4> string:substr("Hello, World!", 8, 2).
"Wo"
string:substr always allocates a new string.

As you can see, string:substr and lists:sublist perform largely identical functions.

Discussion

An additional function in the string module that you should be aware of is sub_string/3. It allows you to get a substring when you know the start and stop index, but don't know the length of the entire string. This could be an efficiency gain for very large strings, since you would not have to call length to find the end point. For example:

5> FileName="C:\\This\\is\\a\\long\\file\\name\\path\\nameIwant.exe".
"C:\\This\\is\\a\\long\\file\\name\\path\\nameIwant.exe"
6> Start = string:rchr(FileName, $\\)
33
7> End = string:rchr(FileName, $.).
43
8> string:sub_string(FileName, 33 + 1, 43 - 1).
"nameIwant"

Contributors

Based on work by GordonWeakliem and NoelWelsh. Many helpful comments and Erlang tips by BengtKleberg.

-- BrentAFulgham - 20 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 030

 
 
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