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

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