doushuhuai7247 2019-09-19 02:45
浏览 74

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

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?

  • 写回答

1条回答 默认 最新

  • dsfsdfsd34324 2019-09-19 02:50
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大