如何在GO编程中更改特定索引处的byte[]中的某些字节?

JSc*_*rtz 3 byte go

我有一个 []byte ,它本质上是一个字符串,在这个数组中我找到了我想使用索引更改的内容:

content []byte
key []byte
newKey []byte
i = bytes.Index(content, key)
Run Code Online (Sandbox Code Playgroud)

所以我在内容中找到了密钥(在索引 I 处),现在我想用 newKey 替换密钥,但我似乎找不到添加它的方法,我正在尝试明显行不通的事情:)

content[i] = newKey
Run Code Online (Sandbox Code Playgroud)

是否有一些函数允许我在 content []byte 中用“newKey”替换“key”?

谢谢,

Von*_*onC 5

按照文章“ Go Slices:用法和内部原理”,您可以使用以下命令copy来创建具有正确内容的切片:

操场

package main

import "fmt"

func main() {
    slice := make([]byte, 10)
    copy(slice[2:], "a")
    copy(slice[3:], "b")
    fmt.Printf("%v\n", slice)
}
Run Code Online (Sandbox Code Playgroud)

输出:

[0 0 97 98 0 0 0 0 0 0]
Run Code Online (Sandbox Code Playgroud)

在你的情况下,如果len(key) == len(newJey)

操场

package main

import "fmt"
import "bytes"

func main() {
    content := make([]byte, 10)
    copy(content[2:], "abcd")
    key := []byte("bc")
    newKey := []byte("xy")
    fmt.Printf("%v %v\n", content, key)

    i := bytes.Index(content, key)
    copy(content[i:], newKey)
    fmt.Printf("%v %v\n", content, newKey)
}
Run Code Online (Sandbox Code Playgroud)

输出:

[0 0 97 98 99 100 0 0 0 0] [98 99]
[0 0 97 120 121 100 0 0 0 0] [120 121]
Run Code Online (Sandbox Code Playgroud)