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?
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With