How to change some bytes in a byte[] at a specific index in GO programming?

huangapple go评论91阅读模式
英文:

How to change some bytes in a byte[] at a specific index in GO programming?

问题

我有一个 []byte,实际上是一个字符串,在这个数组中,我找到了想要通过索引更改的内容:

content []byte
key []byte
newKey []byte
i = bytes.Index(content, key)

所以我在 content 中找到了 key(在索引 I 处),现在我想用 newKey 替换 key,但我似乎找不到一种方法将其添加进去,我尝试了显而易见的不起作用的方法 How to change some bytes in a byte[] at a specific index in GO programming?

content[i] = newKey

是否有一些函数可以在 content []byte 中将 "key" 替换为 "newKey"?

谢谢,

英文:

I have a []byte that which is essentially a string, in this array I have found something I want to change using index:

content []byte
key []byte
newKey []byte
i = bytes.Index(content, key)

So I have found key in content (at index I), now I want to replace key with newKey but I can't seem to find a way to add it in I was trying the obvious thing that wouldn't work How to change some bytes in a byte[] at a specific index in GO programming?

content[i] = newKey

Is there some function that allows me to replace "key" with "newKey" within content []byte?

Thanks,

答案1

得分: 5

根据文章《Go Slices: usage and internals》中的内容,你可以使用copy来创建一个包含正确内容的切片:

playground

package main

import "fmt"

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

输出结果:

[0 0 97 98 0 0 0 0 0 0]

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

playground

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)
}

输出结果:

[0 0 97 98 99 100 0 0 0 0] [98 99]
[0 0 97 120 121 100 0 0 0 0] [120 121]
英文:

Following the article "Go Slices: usage and internals", you can use copy in order to create a slice with the right content:

playground

package main

import "fmt"

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

Output:

[0 0 97 98 0 0 0 0 0 0]

In your case, if len(key) == len(newJey):

playground

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)
}

Output:

[0 0 97 98 99 100 0 0 0 0] [98 99]
[0 0 97 120 121 100 0 0 0 0] [120 121]

huangapple
  • 本文由 发表于 2014年7月19日 11:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/24836517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定