I want to split a String into alternating words. There will always be an even number.
e.g.
val text = "this here is a test sente开发者_运维百科nce"
should transform to some ordered collection type containing
"this", "is", "test"
and
"here", "a", "sentence"
I've come up with
val (l1, l2) = text.split(" ").zipWithIndex.partition(_._2 % 2 == 0) match {
case (a,b) => (a.map(_._1), b.map(_._1))}
which gives me the right results as two Arrays.
Can this be done more elegantly?
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)
So, how about this: scala> val text = "this here is a test sentence" text: java.lang.String = this here is a test sentence
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>
精彩评论