将字符串拆分为交替的单词(Scala)

Lui*_*hys 14 string scala

我想将一个字符串拆分为交替的单词.总会有一个偶数.

例如

val text = "this here is a test sentence"
Run Code Online (Sandbox Code Playgroud)

应该转换为包含的某些有序集合类型

"this", "is", "test"
Run Code Online (Sandbox Code Playgroud)

"here", "a", "sentence"
Run Code Online (Sandbox Code Playgroud)

我想出来了

val (l1, l2) = text.split(" ").zipWithIndex.partition(_._2 % 2 == 0) match {
  case (a,b) => (a.map(_._1), b.map(_._1))}
Run Code Online (Sandbox Code Playgroud)

这给了我两个数组的正确结果.

这可以更优雅地完成吗?

mis*_*tor 29

scala> val s = "this here is a test sentence"
s: java.lang.String = this here is a test sentence

scala> val List(l1, l2) = s.split(" ").grouped(2).toList.transpose
l1: List[java.lang.String] = List(this, is, test)
l2: List[java.lang.String] = List(here, a, sentence)
Run Code Online (Sandbox Code Playgroud)