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,
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
", 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
", content, key)
i := bytes.Index(content, key)
copy(content[i:], newKey)
fmt.Printf("%v %v
", 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]