Kotlin program to print each character of a string (4 different ways)

Introduction :

In this kotlin programming tutorial, we will learn how to print each character of a string in kotlin. The program will take the string as input from the user and print out all characters of it one by one.

We will iterate through each character of a string and print out its value to the user. Actually, there are different ways to iterate through the characters of a string in kotlin. In this tutorial, we will learn four different ways to do it.

Using indices :

This is the most used method. indices is a val that returns the range of valid character indices for a char sequence. Using its value, we will get one IntRange of all index positions.
The program will get all index positions IntRange and it will iterate through them one by one. One great feature of Kotlin is that we can access any character of a string by using its index. For string str, we can get the character of index i like str[i]. Using the same way, our program will print out all characters of the string.
Let’s have a look at the program :

fun main(args: Array) {
    val line:String

    print("Enter a string : ")
    line = readLine().toString()

    for(i in line.indices){
        println(line[i])
    }
}

The output will look like as below :

Enter a string : world
w
o
r
l
d

kotlin print character in string

Using forEach :

forEach is a quick way to iterate through each character of a string in kotlin.

fun main(args: Array) {
    val line:String

    print("Enter a string : ")
    line = readLine().toString()

    line.forEach { c -> println(c) }
}

Sample Output :

Enter a string : kotlin
k
o
t
l
i
n

kotlin print character in string

Using forEachIndexed :

forEachIndexed is another method and you can use it instead of forEach if you need the index position with the character.

fun main(args: Array) {
    val line:String

    print("Enter a string : ")
    line = readLine().toString()

    line.forEachIndexed { i,c -> println("Index $i Character $c") }
}

Sample Output :

Enter a string : world
Index 0 Character w
Index 1 Character o
Index 2 Character r
Index 3 Character l
Index 4 Character d

kotlin print character in string

Iterate by converting the string to an array :

We can first convert the string to an array and then iterate over the characters one by one. We will use toCharArray method. It returns a new character array containing the characters from the caller string. To iterate over this array, we will use one for loop

fun main(args: Array) {
    val line:String

    print("Enter a string : ")
    line = readLine().toString()

    for(c in line.toCharArray()){
        println(c)
    }
}

Sample Output :

Enter a string : apple
a
p
p
l
e

kotlin print character in string

You might also like :

Leave a Reply