Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate list of strings

Say I have list of strings in Ceylon. (It does not have to be a List<String>; it could be an iterable, sequence, array, etc.) What is the best way to concatenate all these strings into one string?

like image 834
drhagen Avatar asked Dec 15 '25 02:12

drhagen


2 Answers

The most efficient solution is to use the static method String.sum(), since that is optimized for a stream of Strings (and uses a StringBuilder) under the covers.

value concat = String.sum(strings);

The other solutions proposed here, while correct, all use generic functions based on Summable, which in principle are slightly slower.

like image 56
Gavin King Avatar answered Dec 16 '25 14:12

Gavin King


Some other suggestions:

Since strings are Summable, you can use the sum function:

print(sum(strings));

Note that this requires a nonempty stream (sum can’t know which value to return for an empty stream); if your stream is possibly-empty, prepend the empty string, e. g. in a named arguments invocation:

print(sum { "", *strings });

You can also use the concatenate function, which concatenates streams of elements, to join the strings (streams of characters) into a single sequence of characters, and then turn that sequence into a proper String again.

print(String(concatenate(*strings)));

And you can also do the equivalent of sum more manually, using a fold operation:

print(strings.fold("")(uncurry(String.plus)));

Try it!

like image 38
Lucas Werkmeister Avatar answered Dec 16 '25 16:12

Lucas Werkmeister