英文:
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,但我似乎找不到一种方法将其添加进去,我尝试了显而易见的不起作用的方法
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
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
来创建一个包含正确内容的切片:
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)
:
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:
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)
:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论