To iterate over characters in a string in Kotlin, you can use various methods such as indices, forEach, or for loop with the char indices.
In this example,
str
with a value of "Hello"
.indices
property of the string to get the range of valid indices for the string.str[index]
.fun main() {
val str = "Hello"
for (index in str.indices) {
println(str[index])
}
}
H e l l o
In this example,
str
with a value of "World"
.forEach
method on the string and provide a lambda function that takes each character as input and prints it.forEach
method iterates over each character in the string.fun main() {
val str = "World"
str.forEach { char ->
println(char)
}
}
W o r l d
In this tutorial, we learned How to Iterate over Characters in String in Kotlin language with well detailed examples.