假设我在Scala中有一个字符串数组:
val strings = Array[String]("1", "2", "3", "4", "5", "6", "7")
我需要的是创建一个新数组,这些元素将作为第一个数组的每三个(任意数量)后续元素的串联获得,这应该导致("123", "456", "7")
作为Scala的新手,我编写了以下代码,既不简洁也不有效:
var step = 3
val strings = Array[String]("1", "2", "3", "4", "5", "6", "7")
val newStrings = collection.mutable.ArrayBuffer.empty[String]
for (i <- 0 until strings.length by step) {
var elem = ""
for (k <- 0 until step if i + k < strings.length) {
elem += strings(i + k)
}
newStrings += elem
}
Scala的做法是什么?
答案 0 :(得分:9)
strings.grouped(3).map(_.mkString).toArray
或
strings grouped 3 map (_.mkString) toArray
我个人更喜欢第一个版本:)
答案 1 :(得分:4)
strings grouped 3 map (_.mkString)
或(为了真正获得Array
)
(strings grouped 3 map (_.mkString)).toArray
答案 2 :(得分:3)
...或使用滑动
val strings = Array[String]("1", "2", "3", "4", "5", "6", "7")
strings.sliding (3, 3) .map (_.mkString).toArray
res19: Array[String] = Array(123, 456, 7)
滑动:你拿3,继续前进3.变种:
scala> strings.sliding (3, 2) .map (_.mkString).toArray
res20: Array[String] = Array(123, 345, 567)
取3,但转发2
scala> strings.sliding (2, 3) .map (_.mkString).toArray
res21: Array[String] = Array(12, 45, 7)
取2,前进3(从而跳过每三分之一)