String Join
From Erlang Community
(Difference between revisions)
| Revision as of 21:53, 18 August 2006 (edit) Cyberlync (Talk | contribs) ← Previous diff |
Current revision (11:10, 30 May 2009) (edit) (undo) MattRussell (Talk | contribs) (join with a separator) |
||
| (One intermediate revision not shown.) | |||
| 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> | ||
| - | [[Category:CookBook]] | + | For example, |
| + | <code> | ||
| + | 3> join(", ", ["foo", "bar", "baz]). | ||
| + | "foo, bar, baz" | ||
| + | </code> | ||
| + | |||
| + | [[Category:CookBook]][[Category:StringRecipes]] | ||
Current revision
[edit] Problem
You need to combine several strings into a larger string.
[edit] 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"
|

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

