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 :
Advertisement
Something interesting
Tutorials
+7.7k Golang : get the current working directory of a running program
+5.7k List of Golang XML tutorials
+6.1k Golang : How to write backslash in string?
+22.9k Golang : Calculate time different
+15.9k Golang : Get file permission
+13.9k Golang : Get current time
+18.2k Golang : Put UTF8 text on OpenCV video capture image frame
+13.5k Golang : How to get year, month and day?
+4.7k Unix/Linux : How to pipe/save output of a command to file?
+6k Golang : Compound interest over time example
+15.6k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+12.9k Golang : Convert IPv4 address to packed 32-bit binary format