如何从Go中的字符串替换nth char [英] How to replace nth char from a string in Go

查看:71
本文介绍了如何从Go中的字符串替换nth char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换原始字符串中的第n个字符.我可以使用 chars [i] 从字符串中访问第n个char,但是当我将值分配给 chars [i] 时,会出现错误.

I want to replace the nth char in the original string. I can access the nth char from the string by using chars[i], but when I assign a value to chars[i], I get an error.

package main
import "fmt"

func main() {
  var chars = "abcdef"
  fmt.Println(string(chars[3]))
  chars[3] = "z" // is not working
}

推荐答案

之所以会这样,是因为 chars 实际上是一个字符串,并且是不可变的.如果适当地声明了它(作为字节片),则可以在尝试时将其分配.这是一个例子.

This is happening because chars is actually a string and is immutable. If you declared it appropriately (as a byte slice) then you can assign to it as you're attempting. Here's an example;

package main
import "fmt"

func main() {
  var chars = []byte{'a', 'b', 'c', 'd', 'e', 'f'}
  fmt.Println(string(chars[3]))
  fmt.Printf("%T\n", chars)
  chars[3] = 'z'
  fmt.Println(string(chars))
}

https://play.golang.org/p/N1sSsfIBQY

或者,您也可以按照其他答案中的说明使用切片.

Alternately you could use reslicing as demonstrated in the other answer.

这篇关于如何从Go中的字符串替换nth char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆