Golang bytes.SplitN() function example

bytes package

SplitN slices the input slice into subslices separated by separator(2nd parameter) and returns a slice of the subslices between those separators. If separator is empty, SplitN splits after each UTF-8 sequence. The count (n) (3rd parameter) determines the number of subslices to return:

n > 0: at most n subslices; the last subslice will be the unsplit remainder.

n == 0: the result is nil (zero subslices)

n < 0: all subslices

Golang bytes.SplitN() function usage example

 package main

 import (
 "fmt"
 "bytes"
 )

 func main() {

 str := []byte("I LOVE THIS WORLD!")

 for i, rune := range bytes.SplitN(str, []byte{' '}, 2) {
 fmt.Printf("Counter %d :  %s\n", i , string(rune))
 }

 fmt.Println("--------------")

 for i, rune := range bytes.SplitN(str, []byte{' '}, 3) {
 fmt.Printf("Counter %d :  %s\n", i , string(rune))
 }

 fmt.Println("--------------")
 for i, rune := range bytes.SplitN(str, []byte{' '}, 4) {
 fmt.Printf("Counter %d :  %s\n", i , string(rune))
 }

 fmt.Println("--------------")
 for i, rune := range bytes.SplitN(str, []byte{' '}, -1) {
 fmt.Printf("Counter %d :  %s\n", i , string(rune))
 }

 }

Output :

Counter 0 : I

Counter 1 : LOVE THIS WORLD!


Counter 0 : I

Counter 1 : LOVE

Counter 2 : THIS WORLD!


Counter 0 : I

Counter 1 : LOVE

Counter 2 : THIS

Counter 3 : WORLD!


Counter 0 : I

Counter 1 : LOVE

Counter 2 : THIS

Counter 3 : WORLD!

Reference :

http://golang.org/pkg/bytes/#SplitN

Advertisement