To search for a substring within a byte slice using the bytes package in Go, you can use the Index
function provided by the package. Here's an example:
package main
import (
"bytes"
"fmt"
)
func main() {
// Example byte slice
byteSlice := []byte("Hello, World!")
// Substring to search for
substring := []byte("World")
// Find the index of the substring in the byte slice
index := bytes.Index(byteSlice, substring)
if index != -1 {
fmt.Printf("Substring '%s' found at index %d\n", string(substring), index)
} else {
fmt.Printf("Substring '%s' not found\n", string(substring))
}
}
In this example, we define a byte slice byteSlice
and a substring substring
that we want to search for in byteSlice
. We then use the Index
method of the bytes package to find the index of the first occurrence of the substring within the byte slice. If the index is not -1, it means that the substring was found, and we can print the index. Otherwise, we print a message indicating that the substring was not found.