亲宝软件园·资讯

展开

Scala中的mkString的具体使用方法

人气:0

1.mkString()方法的使用:

object Test {
 def main(args: Array[String]): Unit = {
 var name : String = "Hello LittleLawson"
 var age :Int = 2
 println(name.mkString)
 println(name.mkString(" "))//separate string with space

 var str0 = "scala"
 println(str0.mkString(","))//separate string with comma

 println(str0.mkString("begin",",","end"))

 /*
 1.mkString is used in the inner List,That is say ,Elements in the list is applied.
  */
 val a = List(1,2,3,4)
 val b = new StringBuilder()
 println(a.mkString("List(" , ", " , ")"))

 }
}

执行结果如下:
Hello LittleLawson
H e l l o   L i t t l e L a w s o n
s,c,a,l,a
begins,c,a,l,aend
List(1, 2, 3, 4)

Process finished with exit code 0

2.scala通过mkString方法把一个集合转化为一个字符串

Problem
    如果你想要把集合元素转化为字符串,可能还会添加分隔符,前缀,后缀。

Solution
    使用mkString方法来打印一个集合内容,下面给一个简单的例子:

scala> val a = Array("apple", "banana", "cherry")
a: Array[String] = Array(apple, banana, cherry)

scala> a.mkString
res3: String = applebananacherry

使用mkString方法你会看到结果并不漂亮,我们来加一个分隔符:

scala> a.mkString(",")
res4: String = apple,banana,cherry

scala> a.mkString(" ")
res5: String = apple banana cherry

这样看起来就好看多了,同样你可以添加一个前缀和一个后缀:

scala> a.mkString("[", ", ", "]")
res6: String = [apple, banana, cherry]

如果你想把一个潜逃集合转化为一个字符串,比如嵌套数组,首先你要展开这个嵌套数组,然后调用mkString方法:

scala> val a = Array(Array("a", "b"), Array("c", "d"))
a: Array[Array[String]] = Array(Array(a, b), Array(c, d))

scala> a.flatten.mkString(",")
res7: String = a,b,c,d

Discussion

你可以调用集合的toString方法,但是它返回带有集合元素信息的集合名称:

scala> val v = Vector("apple", "banana", "cherry")
v: scala.collection.immutable.Vector[String] = Vector(apple, banana, cherry)

scala> v.toString
res8: String = Vector(apple, banana, cherry)
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论