In this tutorial, you shall learn how to insert a character at specific index in a given string in Kotlin, using String.substring() function, with the help of examples.
Kotlin – Insert character at specific index in string
To insert a character at specific index in string in Kotlin, you can use String.substring() function.
Find the substring from starting to the specified index in the string. Then find the substring from the index to the end of the string. Now, concatenate the first part, the character, and the second part into a single string.
Syntax
The syntax to insert character ch
at index index
in string str
is
str.substring(0, index) + ch + str.substring(index)
Examples
1. Insert character ‘m’ at index=4 in string
In the following program, we take a string in str
, and insert the character 'm'
at index=3
.
Main.kt
fun main() {
var str = "hello world"
val ch = 'm'
val index = 3
str = str.substring(0, index) + ch + str.substring(index)
println(str)
}
Output
helmlo world
Related Tutorials
Conclusion
In this Kotlin Tutorial, we learned how to insert a character at specific index in string using String.substring() function.