Reputation: 13
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
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
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