Example: Split, Join, and Equal from BYTES Package


Split slices s into all subslices separated by sep and returns a slice of the subslices between those separators.
Join concatenates the elements of s to create a new byte slice. The separator sep is placed between elements in the resulting slice.
Equal returns a boolean(true or false) reporting whether a and b are the same length and contain the same bytes.

Example

package main

import (
	"bytes"
	"fmt"		
)

func main() {	
	countries := []byte("Australia Canada Japan Germany India")
	space := []byte{' '}
	splitExample := bytes.Split(countries, space)
	fmt.Printf("\nSplit split %q on a single space:", countries)
	for index,element := range splitExample{
        fmt.Printf("\n%d => %q", index, element)
    }
	
	joinChar := []byte{'-'}
	countryJoin := bytes.Join(splitExample,joinChar)
	fmt.Printf("\n\nJoin joins slice with '-' : %q", countryJoin)	
		
	fmt.Printf("\nEqual Checks Byte Slice:%v",bytes.Equal(countryJoin,countries)) // false	
	countryJoin = bytes.Join(splitExample,space)
	fmt.Printf("\nEqual Checks Byte Slice:%v",bytes.Equal(countryJoin,countries)) // true
}

Output

Split split "Australia Canada Japan Germany India" on a single space:
0 => "Australia"
1 => "Canada"
2 => "Japan"
3 => "Germany"
4 => "India"

Join joins slice with '-' : "Australia-Canada-Japan-Germany-India"
Equal Checks Byte Slice:false
Equal Checks Byte Slice:true
Most Helpful This Week