cayajorayu
cayajorayu

Reputation: 13

Scala string to array double quoted elements

In Scala, how can I convert a comma separated string to an array with double quoted elements?

I have tried as below:

var string = "welcome,to,my,world"
var array = string.split(',').mkString("\"", "\",\"", "\"")
Output:
[ "\"welcome\",\"to\",\"my\",\"world\""]

My requirement is for the array to appear as:

["welcome","to","my","world"]

I also tried using the below method:

var array = string.split(",").mkString(""""""", """","""", """"""")
Output:["\"ENV1\",\"ENV2\",\"ENV3\",\"ENV5\",\"Prod\""]

Upvotes: 0

Views: 2789

Answers (2)

Ossip
Ossip

Reputation: 1045

Your question is a bit unclear, as your example result does not contain double quotes. This would generate a string that looks like your requirement, but not sure if that's what you're looking for?

var string = "welcome,to,my,world"
string.split(',').mkString("[\"","\",\"","\"]")`

res9: String = ["welcome","to","my","world"]`

Upvotes: 0

Denis Iakunchikov
Denis Iakunchikov

Reputation: 1349

mkString makes string out of sequence. If you need an array as a result you just need to map the elements to add quotes.

val str = "welcome,to,my,world"

val arr = 
    str
    .split( ',' )
    .map( "\"" + _ + "\"" )

arr.foreach( println )

Output

"welcome"
"to"
"my"
"world"

Upvotes: 4

Related Questions