Erlang Central

String Join

Revision as of 11:10, 30 May 2009 by MattRussell (Talk | contribs)

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"