How to Iterate Over String in Kotlin: Simple Examples
In Kotlin, you can iterate over a string using a
for loop to access each character one by one. Simply write for (char in string) { } to process each character inside the loop.Syntax
To iterate over a string in Kotlin, use a for loop with the syntax for (char in string) { }. Here, char represents each character in the string as the loop runs.
- string: The string you want to loop through.
- char: A variable holding the current character in each iteration.
kotlin
for (char in "hello") { println(char) }
Output
h
e
l
l
o
Example
This example shows how to print each character of a string on a new line using a for loop.
kotlin
fun main() {
val text = "Kotlin"
for (char in text) {
println(char)
}
}Output
K
o
t
l
i
n
Common Pitfalls
One common mistake is trying to use an index-based loop without checking string length, which can cause errors. Another is modifying the string inside the loop, which is not allowed because strings are immutable in Kotlin.
Also, avoid using forEach without understanding it works with lambdas, which might confuse beginners.
kotlin
fun main() {
val text = "hello"
// Wrong: modifying string inside loop (strings are immutable)
// for (char in text) {
// char = 'a' // Error: val cannot be reassigned
// }
// Correct: just read characters
for (char in text) {
println(char)
}
}Output
h
e
l
l
o
Quick Reference
Here is a quick summary of ways to iterate over a string in Kotlin:
| Method | Description | Example |
|---|---|---|
| For loop | Iterate over each character directly | for (c in str) { println(c) } |
| Indices loop | Use indices to access characters by position | for (i in str.indices) { println(str[i]) } |
| forEach | Use lambda to process each character | str.forEach { println(it) } |
Key Takeaways
Use a simple for loop with 'for (char in string)' to iterate over each character.
Strings in Kotlin are immutable; do not try to change characters inside the loop.
You can also use indices or forEach for iteration depending on your needs.
Always ensure your loop respects string length to avoid errors.
Iterating over strings is straightforward and similar to iterating over collections.