Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String into alternating words (Scala)

Tags:

string

scala

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?

like image 563
Luigi Plinge Avatar asked Sep 03 '11 13:09

Luigi Plinge


People also ask

How do you split text in Scala?

Use the split() Method to Split a String in Scala Scala provides a method called split() , which is used to split a given string into an array of strings using the delimiter passed as a parameter. This is optional, but we can also limit the total number of elements of the resultant array using the limit parameter.

What does .split do in Scala?

The split() method in Scala is used to split the given string into an array of strings using the separator passed as parameter. You can alternatively limit the total number of elements of the array using limit.


1 Answers

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)
like image 179
missingfaktor Avatar answered Sep 18 '22 07:09

missingfaktor