Go 替换字符串中特定位置的字符

Go 替换字符串中特定位置的字符,go,Go,我知道方法string.Replace()。如果您确切地知道要替换的内容及其出现的情况,它就会起作用。但是如果我只想替换一个已知位置的字符,我该怎么办呢?我在想这样的事情: randLetter := getRandomChar() myText := "This is my text" randPos := rand.Intn(len(myText) - 1) newText := [:randPos] + randLetter + [randPos + 1:] 但这并不能替换ran

我知道方法
string.Replace()
。如果您确切地知道要替换的内容及其出现的情况,它就会起作用。但是如果我只想替换一个已知位置的字符,我该怎么办呢?我在想这样的事情:

randLetter := getRandomChar()

myText := "This is my text"

randPos :=  rand.Intn(len(myText) - 1)

newText := [:randPos] + randLetter + [randPos + 1:]

但这并不能替换
randPos
处的字符,只需在该位置插入
randLetter
。对吗?

UTF-8是一种可变长度编码。比如说,

package main

import "fmt"

func insertChar(s string, c rune, i int) string {
    if i >= 0 {
        r := []rune(s)
        if i < len(r) {
            r[i] = c
            s = string(r)
        }
    }
    return s
}

func main() {
    s := "Hello, 世界"
    fmt.Println(s)
    s = insertChar(s, 'X', len([]rune(s))-1)
    fmt.Println(s)
}

字符串是字节的只读片。你不能替换任何东西

单个
符文可以由多个字节组成。因此,您应该将
字符串
转换为
符文的(中间)可变片段

myText:=[]符文(“这是我的文本”)
randPos:=rand.Intn(len(myText)-1)
myText[randPos]=randLetter
fmt.Println(字符串(myText))

我已经编写了一些代码,用
替换
替换在
indexofcharacter
中找到的字符。我可能不是最好的方法,但效果很好


@tkausl字符串是不可变的?在语法固定的情况下,代码将
randPos
处的字节替换为
randLetter
。运行代码时是否会产生意外的结果?我假设该示例是一个输入错误,因为它根本无法编译--请显示实际代码并解释什么不按预期工作。对,我不知道您想要什么注意,在处理多字节字符时,为字符串编制索引可能会产生意外行为,由于字符串是按字节索引的,而不是按符文索引的。那么,您的代码所做的就是替换符文,那么为什么要将func命名为
insertChar
?@leadbebebebop:Go
rune
是一个Unicode码点,通常称为字符。请参阅和。请停止仅使用单个字符作为变量名。@Code.IT:No。请阅读Go标准库中的惯用Go。来自Go技术负责人:。@Code.IT:这是一个观点。在堆栈溢出上不允许主要基于意见的问题。他们关门了。
Hello, 世界
Hello, 世X
func replaceAtPosition(originaltext string, indexofcharacter int, replacement string) string {
    runes := []rune(originaltext )
    partOne := string(runes[0:indexofcharacter-1])
    partTwo := string(runes[indexofcharacter:len(runes)])
    return partOne + replacement + partTwo
}