Delete character at specific index in String in Kotlin
To delete character at specific index in a given string in Kotlin, you can use String.substirng()
function.
Find the substring from starting of the string till the position before the given index. This is our first part.
str.substring(0, index)
Then find the substring from after the index till the end of the string. This is our second part.
str.substring(index+1)
Join these two parts to create a string from the original string with the character deleted at the specified index.
str.substring(0, index) + str.substring(index+1)
Examples
Delete character at index=4
In the following program, we take a string in str
and delete the character at index=4
.
Kotlin Program
fun main() {
val str = "abcdefghijk"
val index = 4
val resultString = str.substring(0, index) + str.substring(index+1)
println(resultString)
}
Output
abcdfghijk
Explanation
a b c d f g h i j k <- str
0 1 2 3 4 5 6 7 8 9 <- indices
4 <- index (delete character)
a b c d g h i j k
0 3 5 9
str(0, 4) + str(5)