2017-10-16 109 views
0

在斯卡拉,我怎樣才能將逗號分隔的字符串轉換爲雙引號元素的數組?斯卡拉字符串數組雙引號元素

我曾嘗試如下:

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

我的要求是用於陣列顯示爲:

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

回答

1

mkString

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

我使用下面的方法也嘗試使字符串失序。如果你需要一個數組作爲結果,你只需要映射元素來添加引號。

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

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

arr.foreach(println) 

輸出

"welcome" 
"to" 
"my" 
"world" 
+0

隨着你所建議的解決方案,我所得到的是'輸出爲:[ 「\」 歡迎\ 「」, 「\」 到\ 「」, 「\」 我的\ 「」, 「\」世界\「」 ]' – cayajorayu

+1

字符串數組自然地表示爲'[「something」,「something」]''。你想要額外的雙引號到每個元素 - 在這裏他們是。 –

0

你的問題是有點不清楚,因爲你的榜樣結果不包含雙引號。這會產生一個看起來像你的需求的字符串,但不知道這是你在找什麼?

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

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