Kotlin program to remove character at specific index of a String

Introduction :

String is immutable in Kotlin. If we want to change any character in a string, we can’t directly change it. For that, we need to create one new string modifying the given string. In this tutorial, we will learn different ways to do that in Kotlin.

Method 1 : Using substring :

One way to solve this is by getting the substrings before and after the give index. Put the new character in between them and it will give the new string.

We will use string.substring method to get one substring :

fun main() {
    val givenString = "Hello World"
    val index = 4
    val newChar = 'O'

    val newString = givenString.substring(0, index).plus(newChar).plus(givenString.substring(index + 1))
    print(newString)
}

Here, we are using substring in two places. substring(0, index) returns one substring from index 0 to index-1. substring(index + 1) returns one substring from index+1 to the end of the string.

It will print :

HellO World

Method 2: By converting the string to a character array :

String is immutable, but character array is not. In our case, we can always convert the string to a character array and replace the character at the specific index with the new character. We can again convert that array to string.

Let’s take a look at the below program :

fun main() {
    val givenString = "Hello World"
    val index = 4
    val newChar = 'O'

    val charArrString = givenString.toCharArray()
    charArrString[index] = newChar

    val newString = charArrString.concatToString()
    print(newString)
}

Here, givenString is the provided string. We are replacing the character at position index with newChar.

toCharArray converted the string to a character array and concatToString joined the characters in the array to a string.

It will print the same output as the above one.

Similar tutorials :