Kotlin – Insert Character at specific Index in String

Insert Character at specific Index in String in Kotlin

To insert a character at specific index in a string in Kotlin, you can use StringBuilder.insert() function.

Create a StringBuilder object with the given string str, call insert() function on the StringBuilder object, and pass the index and the character char as arguments.

val sb = StringBuilder(str)
sb.insert(index, char)

insert() function inserts the given character at specific index. You can get the resulting string by calling toString() function on the StringBuilder object.

h  e  l  l  o     w  o  r  l  d     <- str
0  1  2  3  4  5  6  7  8  9  10    <- indices
                     ^ index = 7
              char = p

h  e  l  l  o     w     o  r  l  d
                     ^
                     p

h  e  l  l  o     w  p  o  r  l  d

Examples

Validate if string contains “red”

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 = "hello world"
    val index = 7
    val char = "p"

    val sb = StringBuilder(str)
    sb.insert(index, char)
    val resultingString = sb.toString()
    println(resultingString)
}

Output

hello wporld

Explanation

h  e  l  l  o     w  o  r  l  d     <- str
0  1  2  3  4  5  6  7  8  9  10    <- indices
                     ^ index = 7
              char = p

h  e  l  l  o     w     o  r  l  d
                     ^
                     p

h  e  l  l  o     w  p  o  r  l  d