Skip to main content

Iterate through a String in Kotlin

Kotlin provides a number of ways to iterate through the characters in a String. One option is to use the for loop syntax for(){}. This will iterate over each character in the string, and the variable c will be set to the current character on each iteration.

Another option is to use the forEach function: str.forEach { }. This has a similar effect to the for loop but is more concise.

Kotlin also provides an iterator object that can be used to loop over a string. This approach is more general, as it can be used with any object that implements the Iterator interface. However, it is also more verbose than the other options.

val country = "Sao Tome and Principe";
for (i in 0..country.length-1) {
    println(country[i])
}
country.forEach {
    println(it)
}
for (i in country.indices) {
    println(country[i])
}
val it = country.iterator()
while (it.hasNext()) { 
    val c = it.next()
    println(c)
}

By continuing to use the site, you agree to the use of cookies.