Menu Close

Go – How to split a slice of bytes with separator in go

bytes.Split() function is used to split a slice of bytes with separator in go. It slices a slice of bytes into all sub-slices by separator.

Split() function of bytes package is used to slices s into all sub-slices separated by sep. It returns a slice of the sub-slices between those separators.

Function prototype:

func Split(s, sep []byte) [][]byte

Input parameters:
s: Slice of bytes
sep: byte slice of separator

Returns:
1: It returns all sub-slices separated by sep of slice s.

Explanation on how to split a slice of bytes with separator in go

  • This Split() function finds separator sep in s, starts from beginning, and convert it into sub-slice. It stores sub-slice into 2D slice array.
  • If sep is empty then Split() function splits after each UTF-8 sequence.

Example:

1)
s := []byte("x, y, z")
sep := []byte(",")
bytes.Split(s, sep)

Output:
["x" " y" " z"]

2)
s = []byte("x, y, z")
sep = []byte("")
bytes.Split(s, sep)

Output:
["x" "," " " "y" "," " " "z"]

3)
s = []byte("x,y,z")
sep = []byte("")
bytes.Split(s, sep)

Output:
["x" "," "y" "," "z"]

Example with code:

package main

import (
  "fmt"
  "bytes"
)

func main() {

    // Separated by ","
    s := []byte("x, y, z")
    sep := []byte(",")
    fmt.Printf("1) After split: %q", bytes.Split(s, sep))

    // Empty separator
    s = []byte("x, y, z")
    sep = []byte("")
    fmt.Printf("\n2) After split: %q", bytes.Split(s, sep))
    
    // Having slice s without space and empty separator
    s = []byte("x,y,z")
    sep = []byte("")
    fmt.Printf("\n3) After split: %q", bytes.Split(s, sep))
    
    // None separator in slice s
    s = []byte("x, y, z")
    sep = []byte("abc")
    fmt.Printf("\n4) After split: %q", bytes.Split(s, sep))
    
    // Both slice s and separator sep are empty
    s = []byte("")
    sep = []byte("")
    fmt.Printf("\n5) After split: %q", bytes.Split(s, sep))
    
}

Output:

% go run sample.go

1) After split: ["x" " y" " z"]
2) After split: ["x" "," " " "y" "," " " "z"]
3) After split: ["x" "," "y" "," "z"]
4) After split: ["x, y, z"]
5) After split: []

To learn more about golang, Please refer given below link:

References:

https://golang.org/pkg/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *