Junior — Middle
What methods can be used to replace a specific character or substring within a string?
sobes.tech AI
Answer from AI
In Go, to replace characters or substrings within a string, the functions from the strings package are typically used:
strings.Replace— replaces a specified number of occurrences of a substring with another substring.strings.ReplaceAll— replaces all occurrences of a substring with another.
Example of replacing a character:
import (
"fmt"
"strings"
)
func main() {
s := "hello world"
// Replace all 'l' with 'x'
newStr := strings.ReplaceAll(s, "l", "x")
fmt.Println(newStr) // hexxo worxd
}
To replace a character by index, strings in Go are immutable, so you can convert the string to a rune slice, modify the needed element, and convert back:
s := "hello"
runes := []rune(s)
runes[1] = 'a' // replace 'e'
s = string(runes) // hallo
Thus, for substring replacement, use strings.Replace or strings.ReplaceAll, and for character replacement by position, convert to rune slice.