Erlang Central

Difference between revisions of "String Substrings"

From ErlangCentral Wiki

 
(Delete Spam)
(3 intermediate revisions by 3 users not shown)
Line 50:Line 50:
 
"nameIwant"
 
"nameIwant"
 
</code>
 
</code>
 +
 +
[[Category:CookBook]][[Category:StringRecipes]]

Revision as of 08:05, 22 November 2006

Contents

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.

More Information

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"