0

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\""]

2 Answers 2

4

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"
Sign up to request clarification or add additional context in comments.

2 Comments

With the solution you have suggested , what I get is output is :[ "\"welcome\"", "\"to\"", "\"my\"","\"world\"" ]
Array of strings is naturally represented as [ "something", "something" ]. You wanted additional double quotes to each element - here they are.
0

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"]`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.