14

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 sentence"

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?

elm
  • 20,117
  • 14
  • 67
  • 113
Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180

2 Answers2

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)
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
2

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>
Eastsun
  • 18,526
  • 6
  • 57
  • 81