Kotlin – Iterate over characters in String

Iterate over characters in String in Kotlin

To iterate over the characters in given string in Kotlin, you can use For loop statement.

The syntax to iterate over characters in a string str using For loop is

for (char in str) {
  //your code
}

Examples

Iterate over characters of string “Hello World”

In the following program, we take a string in str and iterate over the characters of the string using For loop.

Kotlin Program

fun main(args: Array<String>) {
    val str = "Hello World"
    for (char in str) {
        println(char)
    }
}

Output

H
e
l
l
o
 
W
o
r
l
d