Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String in a Tuple

Tags:

scala

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"))
like image 467
fleo Avatar asked May 29 '26 11:05

fleo


1 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))
like image 133
Yuval Itzchakov Avatar answered May 31 '26 05:05

Yuval Itzchakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!