Phani Rithvij
Phani Rithvij

Reputation: 4477

How to join a list of integers to a string in Erlang?

I have a list of integers:

X = [1, 2, 3, 4, 5, 6].

I'd like to get the string "1 2 3 4 5 6" as the output.

I've tried string:join(X, " ") but it doesn't work.

I've also tried _X = lists:join(X, " "), but it is resulting in an empty string " ". When I print it erlang:display(_X).

Is there a built-in method in Erlang that does that?

Upvotes: 0

Views: 797

Answers (1)

Steve Vinoski
Steve Vinoski

Reputation: 20004

Both string:join/2 and lists:join/2 will produce the desired result, but both require the integers to be converted to strings first. You can use a list comprehension to do that:

1> X = [1, 2, 3, 4, 5, 6].
[1,2,3,4,5,6]
2> string:join([integer_to_list(I) || I <- X], " ").
"1 2 3 4 5 6"
3> lists:join(" ", [integer_to_list(I) || I <- X]).
["1"," ","2"," ","3"," ","4"," ","5"," ","6"]
4> lists:flatten(lists:join(" ", [integer_to_list(I) || I <- X])).
"1 2 3 4 5 6"

Note that lists:join/2 takes the separator as its first argument while string:join/2 takes it as the second argument.

Note also that lists:join/2 returns a new list where the elements of the input list are separated by the separator. To get a flat list when, as in this case, the separator is also a list, use lists:flatten/1 as shown in the final command above.

And finally, note that string:join/2 is obsolete, and you should use lists:join/2 instead.

Upvotes: 2

Related Questions