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

时间:2011-09-03 13:15:12

标签: string scala

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

e.g。

val text = "this here is a test sentence"

应该转换为包含

的有序集合类型
"this", "is", "test"

"here", "a", "sentence"

我想出了

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

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

这可以更优雅地完成吗?

2 个答案:

答案 0 :(得分:28)

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)

答案 1 :(得分:2)

那么,这个怎么样:     阶> val text =“这是一个测试句子”     text:java.lang.String =这是一个测试句

scala> val Reg = """\s*(\w+)\s*(\w+)""".r
Reg: scala.util.matching.Regex = \s*(\w+)\s*(\w+)


scala> (for(Reg(x,y) <- Reg.findAllIn(text)) yield(x,y)).toList.unzip
res8: (List[String], List[String]) = (List(this, is, test),List(here, a, sentence))

scala>