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?
Concatenate list of strings
150 views Asked by drhagen AtThere are 3 answers
On
You could use "".join, which actually takes {Object*}, so it works on any iterable of objects, not just Strings.
value strings = {"Hello", " ", "world", "!"};
value string = "".join(strings); // "Hello world!"
The string on which the join method is called is the separator. An empty string "" is simple concatenation.
On
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)));
The most efficient solution is to use the static method
String.sum(), since that is optimized for a stream ofStrings (and uses aStringBuilder) under the covers.The other solutions proposed here, while correct, all use generic functions based on
Summable, which in principle are slightly slower.