Search⌘ K
AI Features

Modifying Strings: Inserting, Deleting, and Replacing Characters

Explore how to manipulate immutable strings in Go by performing insertions, deletions, and replacements efficiently. Learn to convert strings to rune slices for modifications, understand the time complexity implications, and apply these techniques to solve real-world string handling problems.

By now you have established the understanding that strings in Go are immutable and that every operation which appears to modify a string is actually producing a new one. That raises a practical question that needs a direct answer: if strings cannot be changed in place, how do we perform the kinds of modifications that real programs and algorithms constantly require? Inserting a character at a specific position, removing an unwanted character, and replacing one substring with another are fundamental operations, and understanding how to perform them correctly and efficiently is what we’ll learn now.

Inserting a character

Inserting a character at a specific position means placing a new character at a given index and shifting every character from that position onward one step to the right to accommodate it.

Consider the string "helo" and the requirement to insert the character 'l' at index 3.

Before: h e l o
Index: 0 1 2 3
After: h e l l o
Index: 0 1 2 3 4

The character 'o' that was at index 3 has moved to index 4 to make room for the inserted character. In general, inserting at position ii requires shifting every character from index ii to the end of the string one position to the right. In the worst case, inserting at the beginning of the string requires shifting all nn existing characters, making insertion an O(n)O(n) operation.

Insertion method 1

In Go, because strings are immutable, one common approach is to convert the string to a slice of runes, perform the insertion on the slice, and convert the result back into a string. Since slices do not have a built-in insert method, we make room with append and copy, then place the new rune at the target index.

Go (1.24.2)
package main
import "fmt"
func main() {
s := "helo"
chars := []rune(s)
chars = append(chars, 0)
copy(chars[4:], chars[3:])
chars[3] = 'l'
result := string(chars)
fmt.Printf("Original string: \"%s\"\n\n", s) // Original string: helo
fmt.Printf("After insertion: \"%s\"\n", result) // After insertion: hello
}

The conversion to a rune slice costs O(n)O(n) ...