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

1 Answer

0 votes
fun countWordOccurrences(str: String): Map<String, Int> {
    // Split the str into words, using whitespace and punctuation as delimiters
    val words = str.split("\\W+".toRegex()).filter { it.isNotEmpty() }

    // Create a map to store the word counts
    val wordCountMap = mutableMapOf<String, Int>()

    // Iterate through the words and count their occurrences
    for (word in words) {
        val lowerCaseWord = word.lowercase() // Convert to lowercase for case-insensitive counting
        wordCountMap[lowerCaseWord] = wordCountMap.getOrDefault(lowerCaseWord, 0) + 1
    }

    return wordCountMap
}

fun main() {
    val str = "Kotlin is a cross-platform, statically typed, " + 
    		  "general-purpose high-level programming language " + 
    		  "with type inference. Kotlin is designed to " + 
    		  "interoperate fully with Java"
    
    val wordOccurrences = countWordOccurrences(str)
    
    for ((word, count) in wordOccurrences) {
        println("$word: $count")
    }
}
 
 
    
/*
run:
 
kotlin: 2
is: 2
a: 1
cross: 1
platform: 1
statically: 1
typed: 1
general: 1
purpose: 1
high: 1
level: 1
programming: 1
language: 1
with: 2
type: 1
inference: 1
designed: 1
to: 1
interoperate: 1
fully: 1
java: 1
  
*/

 



answered Mar 2, 2025 by avibootz
...