Kotlin – Iterate over words in String

Iterate over words in String in Kotlin

To iterate over words in given string in Kotlin, split the string into words using String.split() function, and use a For loop statement to iterate over the words.

Examples

Iterate over words of given string

In the following program, we take a string in str, split the string into words by single space character, and iterate over the words.

Kotlin Program

fun main() {
    val str = "Hello, World! Welcome to Kotlin."
    
    val words = str.split(" ")
    
    for (word in words) {
        println(word)
    }
}

Output

Hello,
World!
Welcome
to
Kotlin.