In this tutorial, you shall learn how to iterate over characters in a given string in Kotlin, using For loop statement or String.forEach() function, with examples.
Kotlin – Iterate over Each Character in the String
Method 1 – Using For loop
To iterate over each character in the String in Kotlin, use String.iterator() method which returns an iterator for characters in this string, and then use For Loop with this iterator.
In the following example, we take a string in str1
, and iterate over each character in this string using String.iterator() method and For Loop.
Main.kt
fun main(args: Array<String>) {
var str = "hello world"
for (ch in str.iterator()) {
println(ch)
}
}
Output
h
e
l
l
o
w
o
r
l
d
Method 2 – Using String.forEach()
To iterate over each character in the String in Kotlin, use String.forEach() method.
In the following example, we take a string in str1
, and iterate over each character in this string using String.forEach() method.
Main.kt
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.