2

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?

drhagen
  • 8,331
  • 8
  • 53
  • 82

3 Answers3

3

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!

Lucas Werkmeister
  • 2,584
  • 1
  • 17
  • 31
3

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.

Gavin King
  • 3,182
  • 1
  • 13
  • 11
  • Hmm, why is this named `sum`? While I understand that it applies the `+` operation, it is nothing like a usual mathematical sum (e.g. not commutative). – Paŭlo Ebermann Apr 09 '18 at 18:29
  • `String`s are [`Summable`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.3.1/module-doc/api/Summable.type.html). They form a monoid, but not a commutative group. – Gavin King Apr 10 '18 at 13:58
2

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.

drhagen
  • 8,331
  • 8
  • 53
  • 82