This article explores different ways to replace the character at a specific index in a Kotlin string.

Strings are immutable in Kotlin. That means their values cannot be changed once created. To replace the character in a string, you will need to create a new string with the replaced character.

1. Using substring() function

The idea is to use the substring() function to partition the string into two halves consisting of substring before and after the character to be replaced. Once you have isolated the character to be replaced, you can use the + operator to build the final string.

Download Code

2. Using StringBuilder instance

You can also use the StringBuilder class to efficiently replace the character at a specific index in a string in Kotlin.

Download Code

3. Using Character array

Another plausible way to replace the character at the specified index in a string is using a character array. The trick is to convert the given string to a character array using its toCharArray() function and then replace the character at the given index. Finally, convert the character array back to the string with the String constructor.

Download Code

That’s all about replacing a character at a specific index in a Kotlin string.