To insert a character at a specific index in a string in Kotlin, you can use the `String.insert()` extension function.
In this example,
str
with a value of "Hello World"
.insert()
extension function to insert the character '!'
at index 5
.str
.fun main() {
var str = "Hello World"
str = str.insert(5, '!')
println(str)
}
fun String.insert(index: Int, element: Char): String {
return if (index in 0..length) {
substring(0, index) + element + substring(index)
} else {
this
}
}
Hello! World
In this tutorial, we learned How to Insert Character at Specific Index in String in Kotlin language with well detailed examples.