In this tutorial, you shall learn how to count the number of words in a given string in Kotlin, using String.split() function, with the help of examples.

Kotlin – Count number of words in string

To count number of words in string in Kotlin, you can use String.split() function and List.count() functions.

The function String.split() can help split the string by one or more whitespace characters, and then we can count the number of split parts returned by the function using List.count().

Syntax

If str is the given string, then the syntax to count the number of words in the string is

</>
Copy
str.split("\\s+".toRegex()).count()

Examples

1. Split values in string separated by comma

In the following program, we take a string in str, and count the number of words in this string.

Main.kt

</>
Copy
fun main() {
    val str = "The quick brown fox jumps over the lazy dog."
    val words = str.split("\\s+".toRegex())
    val count = words.count()
    println("Number of words: $count")
}

Output

Number of words: 9

Related Tutorials

Conclusion

In this Kotlin Tutorial, we learned how to count the number of words in a given string using String.split() and List.count() functions.