RamonBoza
RamonBoza

Reputation: 9038

Scala split Array by comma and each item by quotes

I need to split an array by comma in scala and each item by quotes.

scala offers mkString to split items, the following example uses it:

val args = Array("Hello", "world", "it's", "me")
val string = args.mkString(",")

And the result is:

Hello,world,it's,me

but I need each element enclosed by quotes as in the following example:

"Hello","world","it's","me"

I can implement it using a map like the following one

args.map(entry => s""""${entry}"""" ).mkString(",")

is there any builtin operation that does the same in a more polite way ?

Thanks!

Upvotes: 1

Views: 1471

Answers (2)

Aditya Singh
Aditya Singh

Reputation: 16660

Or maybe use the version of mkString with option to provide prefix and suffix as below:

val args = Array("Hello", "world", "it's", "me")
args.mkString(""""""", """","""", """"""")

Upvotes: 2

Nikita
Nikita

Reputation: 4515

Your solution looks fine. The shorter version could be s"\"$s\"" but it currently doesn't work: https://issues.scala-lang.org/browse/SI-6476

Upvotes: 0

Related Questions