简体   繁体   English

如何修改字符串中的特定字符

[英]How to modify a specific character in a string

In C, We define the character of a string as Char.在 C 中,我们将字符串的字符定义为 Char。 So I want to change a character of a string in Go.所以我想改变 Go 中字符串的一个字符。

if sum%11 != int(str[strlen-1]) {
    str[strlen-1] = byte(sum % 11)
    //fmt.Printf("%T %T\n", str[strlen-1], byte(sum%11))
} else {
    fmt.Println(sum)
}

But it will report an error "cannot assign to str[strlen - 1]".但是会报错“cannot assign to str[strlen - 1]”。 Both str[strlen-1] and byte(sum%11) are uint8. str[strlen-1] 和 byte(sum%11) 都是 uint8。 Why is it wrong?为什么是错的? How should I convert?我应该如何转换?

Unlike in C, Go strings are immutable, so you cannot modify individual bytes in a string.与 C 不同,Go 字符串是不可变的,因此您不能修改字符串中的单个字节。 However, you can convert the string to a byte array, change that, and convert that byte array to string.但是,您可以将字符串转换为字节数组,对其进行更改,然后将该字节数组转换为字符串。

arr:=[]byte(str)
arr[strlen-1]=byte(sum%11)
str=string(arr)

Note that Go strings are UTF-8 encoded.请注意,Go 字符串是 UTF-8 编码的。 A rune may be represented as multiple bytes.一个符文可以表示为多个字节。 By modifying strings like this you may end up with an invalid string.通过像这样修改字符串,您可能会得到一个无效的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM