Iterate over characters of a string in Kotlin
This article explores different ways to iterate over characters of a string in Kotlin.
1. Using index-based for-loop
The standard approach to iterate over characters of a string is with index-based for-loop. The idea is to iterate over a range of valid indices with a range expression.
|
1 2 3 4 5 6 7 |
fun main() { val str = "Kotlin!" for (i in 0..str.length-1) { println(str[i]) } } |
Output:
K
o
t
l
i
n
!
You can also use until, which returns a range starting from a value to but excluding the specified ending value.
|
1 2 3 4 5 6 7 |
fun main() { val str = "Kotlin!" for (i in 0 until str.length) { println(str[i]) } } |
Output:
K
o
t
l
i
n
!
Since strings in Kotlin exposes indices property, you can iterate this way:
|
1 2 3 4 5 6 7 |
fun main() { val str = "Kotlin!" for (i in str.indices) { println(str[i]) } } |
2. Loop over elements
The for-loop iterates through anything that provides an iterator. So, you can replace for-loop over indices with a loop over elements, as shown below:
|
1 2 3 4 5 6 7 |
fun main() { val str = "Kotlin!" for (c in str) { println(c) } } |
Output:
K
o
t
l
i
n
!
3. Using forEach() function
Another equivalent approach is to call the foreach() function on a string with lambda expressions.
|
1 2 3 4 |
fun main() { val str = "Kotlin!" str.forEach { println(it) } } |
Output:
K
o
t
l
i
n
!
That’s all about iterating over characters of a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)