To insert a character at a specific index in a string in Go, you can convert the string to a rune slice, insert the character at the desired index, and then convert it back to a string.
In this example,
str
with a value of "Hello World"
.'!'
at index 5
in the rune slice.package main
import (
"fmt"
)
func main() {
str := "Hello World"
r := []rune(str)
r = append(r[:5], append([]rune{'!'}, r[5:]...)...)
str = string(r)
fmt.Println(str)
}
Hello! World
In this tutorial, we learned How to Insert Character at Specific Index in String in Go language with well detailed examples.