319

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 ",").

0

1 Answer 1

511

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Note that the foldLeft implementation assumes a non-empty list
Thanks! In case anyone wants to enclose string elements in quotes, mkString is also helpful: theStrings.mkString("'", "','", "'")
@Frawr That page links to a bunch of examples oldfashionedsoftware.com/2009/07/30/… which includes an implementation that uses pattern matching for the empty list (Nil) case. Modifying it to mimic mkString would be like this: def mkFoldLeftString[A](list:List[String], delim:String = ","): String = list match { case head :: tail => tail.foldLeft(head)(_ + delim + _) case Nil => "" }
The langref.org link is dead

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.