Scala: join an iterable of strings

StringScala

String Problem Overview


How do I "join" an iterable of strings by another string in Scala?

val thestrings = Array("a","b","c")
val joined = ???
println(joined)

I want this code to output a,b,c (join the elements by ",").

String Solutions


Solution 1 - String

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionscala_newbieView Question on Stackoverflow
Solution 1 - StringBrian AgnewView Answer on Stackoverflow