In this tutorial, you shall learn how to remove a character at specific index in a given string in Kotlin, using String.substring() function, with examples.
Kotlin – Remove character at specific index in String
To remove character at specific index in string in Kotlin, we can use String.substring() function.
First find the substring from starting of the string to just before the specified index. Then find the substring from after the specified index to till the end of the string. Concatenate these two strings, to get a string with the character removed from the original string at specified index. Assign the resulting string to the original string variable itself.
Syntax
If str
is the given string, then the syntax of the statement to remove the character at specific index i
is
str = str.substring(0,i) + str.substring(i+1)
Example
In the following program, we take a string in str
, remove the first character at index=5, and print the output.
Main.kt
fun main() {
var str = "helloworld"
var i = 5
str = str.substring(0,i) + str.substring(i+1)
println(str)
}
Output
helloorld
Explanation
h e l l o w o r l d
0 1 2 3 4 5 6 7 8 9
5 <- remove char at this index
h e l l o o r l d <- resulting string
Conclusion
In this Kotlin Tutorial, we learned how to remove character at specific index in a string using String.substring() function.