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.

Download Code

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.

Download Code

Output:

K
o
t
l
i
n
!

 
Since strings in Kotlin exposes indices property, you can iterate this way:

Download Code

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:

Download Code

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.

Download Code

Output:

K
o
t
l
i
n
!

That’s all about iterating over characters of a string in Kotlin.