To replace a character at a specific index in a string in Go, you can convert the string to a byte slice, modify the byte at the desired index, and then convert the byte slice back to a string.
In this example,
str
.[]byte(str)
.index
with the character newChar
.string(byteSlice)
.str
.package main
import (
"fmt"
)
func main() {
str := "Hello World"
index := 6
newChar := 'x'
byteSlice := []byte(str)
byteSlice[index] = byte(newChar)
str = string(byteSlice)
fmt.Println(str)
}
Hello xorld
In this tutorial, we learned How to Replace Character at Specific Index in String in Go language with well detailed examples.