How to split a byte slice into substrings based on a delimiter using the bytes package in Go?

To split a byte slice into substrings based on a delimiter using the bytes package in Go, you can follow these steps:

  1. Import the necessary packages:
import ( "bytes" "fmt" )
  1. Obtain the byte slice and delimiter:
data := []byte{97, 98, 99, 32, 100, 101, 102} delimiter := []byte{32} // Delimiter is a single space character
  1. Use the bytes.Split() function to split the byte slice into substrings based on the delimiter:
substrings := bytes.Split(data, delimiter)
  1. Print the results:
for _, substring := range substrings { fmt.Println(string(substring)) }

The complete code will look like this:

package main import ( "bytes" "fmt" ) func main() { data := []byte{97, 98, 99, 32, 100, 101, 102} delimiter := []byte{32} // Delimiter is a single space character substrings := bytes.Split(data, delimiter) for _, substring := range substrings { fmt.Println(string(substring)) } }

When you run this code, it will split the byte slice into substrings based on the delimiter, printing each substring on a new line.