Home > Basic > String concatenation

String concatenation

February 25th, 2009

As we all know, Erlang treats String as the array of integers, hence operations on list are applicable on String. 

String concatenation can be done in different ways in Erlang

1> X="I love ".
"I love "
2> Y="Erlang".
"Erlang"
3> string:concat(X, Y).
"I love Erlang"
4> string:join([X, Y], "").
"I love Erlang"
5> X ++ Y.
"I love Erlang"
6> lists:append(X, Y).
"I love Erlang"
7> lists:concat([X, Y]).
"I love Erlang"

Basic ,

  1. Fabian Alenius
    May 8th, 2009 at 07:03 | #1

    You could also do X ++ Y, I’m not sure if it’s just syntactic sugar for lists:concat(…) or not but I suspect it might be.

  2. Fabian Alenius
    May 8th, 2009 at 07:09 | #2

    Ops, I’m blind. Seems you already have an example of ++.

  3. trung
    May 10th, 2009 at 07:15 | #3

    Thanks, Fabian.
    I’ve looked at the source code for lists.erl, your’re right, lists:concat/1 uses ++ for concatenation:

    concat(List) ->
    flatmap(fun thing_to_list/1, List).

    thing_to_list(X) when is_integer(X) -> integer_to_list(X);
    thing_to_list(X) when is_float(X) -> float_to_list(X);
    thing_to_list(X) when is_atom(X) -> atom_to_list(X);
    thing_to_list(X) when is_list(X) -> X. %Assumed to be a string

    flatmap(F, [Hd|Tail]) ->
    F(Hd) ++ flatmap(F, Tail);

  4. July 15th, 2009 at 18:57 | #4

    Hi Trung,

    According to Programming Erlang, the source for the lists module is only an illustrative implementation. Use of ++ is discouraged for all but trivially small lists.

    -Denny

  5. trung
    July 16th, 2009 at 06:48 | #5

    Thanks Denny for the comment.
    Hmm, I though initially that ++ is quite native, why they used it in lists:concat/1 implementation then?

  6. Ben Xu
    August 21st, 2012 at 23:00 | #6

    @Denny Abraham
    I was also confused about “++” vs. “lists:concat”, then I write a simple test, it seems “lists:concat” was obviously faster. I think Denny is right, the BIFs may not be implemented in Erlang indeed.
    The “string:concat/2″ seems not very useful compared to “lists:concat/1″, since it only takes two arguments.
    Hope the author will make a comparison to these functions ;)

  1. No trackbacks yet.