Replace character at specific index in Kotlin
To replace character at specific index in a string with a new character in Kotlin, you can use StringBuilder.setCharAt() function.
Create a StringBuilder object with the given string str, call setCharAt() function on the StringBuilder object, and pass the index and new character newChar as arguments.
val sb = StringBuilder(str)
sb.setCharAt(index, newChar)
replace() function replaces all the occurrences of the substring oldValue with newValue, and returns the resulting string. The original string remains unchanged. We can store the returned value in a variable.
Examples
Replace character at index=2 with ‘m’
Consider a scenario where the word "red" is misspelled in an article as "rlb". We need to use String.replace() function to replace the old value with the new old and correct the string.
Kotlin Program
import java.lang.StringBuilder
fun main() {
val str = "apple"
val index = 2
val newChar = 'm'
val sb = StringBuilder(str)
sb.setCharAt(index, newChar)
val resultingString = sb.toString()
println(resultingString)
}
Output
apmle