将字符串转换为带引号元素的字符串

时间:2015-10-09 07:54:12

标签: scala

在Scala中,如何将逗号分隔的字符串转换为数组为带引号的字符串?

E.g。在R我使用:

var bold_statement_string = "narcos,is,maybe,better,than,the,wire"
var bold_statement_array = bold_statement.split(',')
s"'${bold_statement_array.mkString("','")}'"
Out[83]:
'narcos','is','maybe','better','than','the','wire'

在Scala中,它适用于:

SimpleDateFormat

在python中,我听说总有一种pythonic方式。有更多的Scala-esk方式吗?或者我应该为找到解决方案感到高兴,无论它是否更优雅?

5 个答案:

答案 0 :(得分:10)

首先,在Scala中我们使用val而不是var。我们希望尽可能地接受不变性事物。

val bold_statement_string = "narcos,is,maybe,better,than,the,wire"

第二个你不需要使用字符串插值,mkString可以带一个前缀和一个后缀,它给我们:

bold_statement_string.split(",").mkString("'", "', '", "'")

答案 1 :(得分:0)

试试这个:     对于数组:

scala> bold_statement_string.split(",") map {"\'%s\'".format(_)}
res8: Array[String] = Array('narcos', 'is', 'maybe', 'better', 'than', 'the', 'wire')

For String:

 scala> bold_statement_string.split(",") map {"\'%s\'".format(_)} mkString ","
res9: String = 'narcos','is','maybe','better','than','the','wire'

答案 2 :(得分:0)

在建议的示例中,用逗号分割字符串并用逗号重建字符串会产生相同的初始字符串。对于简单包装带单引号的字符串的情况,请考虑使用mkString

bold_statement_string.mkString("'","","'")

将字符串视为Seq[Char],并在前面添加并附加单引号字符。

答案 3 :(得分:0)

这是最简单的方法。

val bold_statement_string = "narcos,is,maybe,better,than,the,wire"
bold_statement_string
  .split(",")              // Split with comma
  .map("'" + _  + "'")     // Wrap with single quote
  .mkString(","))          // make string with comma

答案 4 :(得分:-1)

这是一个更通用的版本,它使用典型的Scala方法,使用map引用数组元素,foldLeft将它们组合在一起。

val arr = bold_statement_string.split(",").map( v => s"'$v'" )

arr.foldLeft("")( (soFar,v) => if (v=="") v else soFar + ", " + v )
    // fold left starts with the value "" and then invokes the function
    // provided for every element in the collection which combines them
    // 
    // ("","'narcos'") goes to "'narcos'"
    // ("'narcos'", "'is'") goes to "'narcos', 'is'"
    // ("'narcos', 'is'", "'maybe'") goes to "'narcos', 'is', 'maybe'" 
    // and so on 
    // up to the last element giving us the target string
    // 'narcos', 'is', 'maybe', 'better', 'than', 'the', 'wire'

这是一个以相同方式工作的变体,而不是使用if / else它使用更多功能的Scala匹配。

bold_statement_string.split(",").map( v => s"'$v'" ).foldLeft("") {
  case ("",v) => v
  case (soFar,v) => s"$soFar, $v"
}