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

In C, We define the character of a string as Char. So I want to change a character of a string in Go.

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

But it will report an error "cannot assign to str[strlen - 1]". Both str[strlen-1] and byte(sum%11) are 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. 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. A rune may be represented as multiple bytes. By modifying strings like this you may end up with an invalid string.