Menu Close

Go – Split byte slice on whitespace in go

Here, bytes.Fields() function is used to split byte slice on whitespace in go where white space is defined by unicode.IsSpace.

Fields() built-in function of bytes package splits the slice around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace. It returns a slice of subslices of s or an empty slice if s contains only white space.

bytes.Fields() function prototype:

func Fields(s []byte) [][]byte

Input parameters:
s: slice of bytes

Return:
It returns a slice of subslices of s or an empty slice if s contains only white space.

Explanation on split byte slice on whitespace in go

1)
s := []byte("foo bar 123 4  baz")

Output:
["foo" "bar" "123" "4" "baz"]

2)
s := []byte("1 2 3 4 5")

Output:
["1" "2" "3" "4" "5"]

Example:

Code 1:

package main

import (
    "fmt"
    "bytes"
)


func main() {
    s := []byte("foo bar 123 4  baz")
    
    fmt.Printf("\nFields are: %q", bytes.Fields(s))
    
    
    s = []byte("1 2 3 4 5")
    
    fmt.Printf("\nFields are: %q", bytes.Fields(s))
    
    
    s = []byte("")
    
    fmt.Printf("\nFields are: %q", bytes.Fields(s))
}

Output:

% go run sample.go

Fields are: ["foo" "bar" "123" "4" "baz"]
Fields are: ["1" "2" "3" "4" "5"]
Fields are: []

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

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

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