Replace a character at a specific index in a Kotlin string
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.
|
1 2 3 4 5 6 7 8 9 |
fun main() { var string = "Kotlin 1.3" val char = '_' val index = 6 string = string.substring(0, index) + char + string.substring(index + 1) println(string) // Kotlin_1.3 } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { var string = "Kotlin 1.3" val char = '_' val index = 6 val sb = StringBuilder(string).also { it.setCharAt(index, char) } string = sb.toString() println(string) // Kotlin_1.3 } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { var string = "Kotlin 1.3" val char = '_' val index = 6 val chars = string.toCharArray() chars[index] = char string = String(chars) println(string) // Kotlin_1.3 } |
That’s all about replacing a character at a specific index in a Kotlin string.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)