Split String in a Tuple

Viewed 62

In a function def a(l: List[(Int, String)]): List[(Int, String)] = ??? I want to split a String into their words in lower case. Commas etc. should be ignored, so I guess I need replaceAll("[^A-Za-z]+", " ").toLowerCase() somewhere? The Int value should stay the same as in the sentence.

Example how it should work:

val example = List((11, "That is great!"), (12, "Wow, impossible!"))
print(a(example)) 

Result

List((11, "that"),(11, "is"),(11, "great"),(12, "wow"),(12, "impossible"))
2 Answers

You can use flatMap for that:

val example = List((11, "That is great!"), (12, "Wow, impossible!"))
example.flatMap { case (int, str) =>
  str
    .replaceAll("[^A-Za-z]+", " ")
    .toLowerCase()
    .split(' ')
    .map((int, _))
}

Yields:

res0: List[(Int, String)] = List((11,that), (11,is), (11,great), (12,wow), (12,impossible))

This is strictly equivalent to Yuval's answer, but probably more approachable when starting with Scala

for {
  (int, str) <- example
  word <- str.replaceAll("[^A-Za-z]+", " ").toLowerCase().split(' ')
} yield (int, word)

Related