How to count the occurrences of each word in a string with Scala

1 Answer

0 votes
object WordCount extends App {
  val str = "Scala is a strong statically typed high-level general-purpose " + 
            "programming language. Scala supports both object-oriented " + 
            "programming and functional programming."

  // Split the str into words, convert to lowercase, and filter out empty strings
  val words = str.toLowerCase.split("\\W+").filter(_.nonEmpty)

  // Count the occurrences of each word
  val wordCount = words.groupBy(identity).view.mapValues(_.size).toMap

  wordCount.foreach { case (word, count) => println(s"$word: $count") }
}



/*
run:

is: 1
programming: 3
oriented: 1
a: 1
strong: 1
purpose: 1
supports: 1
scala: 2
both: 1
functional: 1
level: 1
statically: 1
typed: 1
object: 1
general: 1
language: 1
and: 1
high: 1
 
*/

 



answered Mar 2, 2025 by avibootz
...