Kotlin – Iterate over Each Character in the String

To iterate over each character in the String in Kotlin, use String.forEach() method.

Given a string str1, and if we would like to perform an action for each character in the String, call forEach() method on string str1 and provide the action action as argument to the method as shown below.

str1.forEach(action: (Char) -> Unit)

forEach() method performs the action on each character.

Example 1 – Check if String Ends with Specified String Value

In this example, we will take a string in str1, and iterate over each character in this string using String.forEach() method.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "ABCD"
    val result = str1.forEach ({ it ->
        println(it)
    })
    println("Filtered String  : " + result)
}

Output

A
B
C
D

Conclusion

In this Kotlin Tutorial, we learned how to iterate over the character of give String, using String.forEach() method, with the help of Kotlin example programs.