icz*_*cza 5
Go 中的字符串是不可变的,你不能改变它们的内容。要更改字符串变量的值,您必须分配一个新的字符串值。
string
s := []byte(str[0])
s[2] = 'y'
str[0] = string(s)
fmt.Println(str)
这将输出(在Go Playground上尝试):
[teyt testing]
bytestring
[]rune
s := []rune(str[0])
s[2] = 'y'
str[0] = string(s)
fmt.Println(str)
在这个例子中,虽然无关紧要,但一般来说可能是这样。
strings.Replace()
func Replace(s, old, new string, n int) string
n
str[0] = strings.Replace(str[0], "s", "y", 1)
另一种解决方案可能是将字符串切片直到可替换字符,并从可替换字符之后的字符开始,然后将它们连接起来(在Go Playground上试试这个):
str[0] = str[0][:2] + "y" + str[0][3:]
这里也必须小心:切片索引是字节索引,而不是字符(符文)索引。