Search code examples
stringscalasplitdouble-quotes

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

Solution

  • 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"