Kotlin program to access a character in a string by index

Introduction :

This kotlin program is to show you how we can access a character in a string using index position. The program will take one string as input from the user. Next, it will take the index position. The output of the program will be the character at that user defined index position in the string. We will learn two different ways to solve this program.

Using [] :

In Kotlin, we can access any character in string str using its index i like str[i]. The index starts from 0. So, str[0] will print the first character in the string. For example :

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

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

    print("Enter the index : ")
    index = readLine()?.toInt() ?: 0

    print("Character at $index in '$line' is : ${line[index]}")
}

Sample Output :

Enter a string : hello
Enter the index : 0
Character at 0 in 'hello' is : h

Enter a string : hello
Enter the index : 4
Character at 4 in 'hello' is : o

The above program will throw one StringIndexOutOfBoundsException if the index is not valid. For example :

Enter a string : hello
Enter the index : 7
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7

We should add one safety check before accessing the character. We will add it to the below example :

Using get(index) :

We can also use get(index) method to get the character at any specific index of a string in Kotlin.

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

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

    print("Enter the index : ")
    index = readLine()?.toInt() ?: -1

    if (index >= line.length) {
        print("Invalid index")
    } else {
        print("Character at $index in '$line' is : ${line.get(index)}")
    }
}

In this example, we have also added one if-else loop to check if the index is valid or not. If it is not valid, we are showing one message to avoid StringIndexOutOfBoundsException. The output of this program will look like as below :

Enter a string : world
Enter the index : 0
Character at 0 in 'world' is : w

Enter a string : world
Enter the index : 2
Character at 0 in 'world' is : r

Enter a string : world
Enter the index : 11
Invalid index

kotlin access character in a string

Conclusion :

It is a good practice to perform a safety check before every possible operation. You can use any of the methods we have described above, but the first one is more preferable. Try to run these examples and if you have any question, don’t hesitate to drop a comment below.

You might also like :