Erlang Central

Difference between revisions of "String Join"

From ErlangCentral Wiki

(join with a separator)
Line 18:Line 18:
 
++ and lists:append will always allocate a new string.  
 
++ and lists:append will always allocate a new string.  
  
 +
If you want to join several strings together using a separator, you can use the following function:
 +
<code>
 +
join(Xs, Xss) -> lists:append(intersperse(Xs, Xss)).
  
 +
intersperse(_, []) -> [];
 +
intersperse(_, [X]) -> [X];
 +
intersperse(Sep, [X|Xs]) -> [X|[Sep|intersperse(Sep, Xs)]].
 +
</code>
 +
 +
For example,
 +
<code>
 +
3> join(", ", ["foo", "bar", "baz]).
 +
"foo, bar, baz"
 +
</code>
  
 
[[Category:CookBook]][[Category:StringRecipes]]
 
[[Category:CookBook]][[Category:StringRecipes]]

Revision as of 11:10, 30 May 2009

Problem

You need to combine several strings into a larger string.

Solution

The built-in concatenation operator (++) is the de-facto answer here:

1> "Some " ++ "text " ++ "and" ++ " stuff".
"Some text and stuff"

You can also use the lists:append function:

2> lists:append(["Some ", "text ", "and", " stuff"]).
"Some text and stuff"

++ and lists:append will always allocate a new string.

If you want to join several strings together using a separator, you can use the following function:

join(Xs, Xss) -> lists:append(intersperse(Xs, Xss)).

intersperse(_, []) -> [];
intersperse(_, [X]) -> [X];
intersperse(Sep, [X|Xs]) -> [X|[Sep|intersperse(Sep, Xs)]].

For example,

3> join(", ", ["foo", "bar", "baz]).
"foo, bar, baz"