Golang bytes.SplitAfterN() function example
package bytes
SplitAfterN slices the input slice into subslices after each instance of separator(2nd parameter) and returns a slice of those subslices. If separator is empty, SplitAfterN 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.SplitAfterN() function usage example
package main
import (
"fmt"
"bytes"
)
func main() {
str := []byte("I LOVE THIS WORLD!")
for i, rune := range bytes.SplitAfterN(str, []byte{' '}, 2) {
fmt.Printf("Counter [%d] : %s\n", i , string(rune))
}
fmt.Println("--------------")
for i, rune := range bytes.SplitAfterN(str, []byte{' '}, 3) {
fmt.Printf("Counter [%d] : %s\n", i , string(rune))
}
fmt.Println("--------------")
for i, rune := range bytes.SplitAfterN(str, []byte{' '}, 4) {
fmt.Printf("Counter [%d] : %s\n", i , string(rune))
}
fmt.Println("--------------")
for i, rune := range bytes.SplitAfterN(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
+10k Golang : Get escape characters \u form from unicode characters
+12.5k Golang : Arithmetic operation with numerical slices or arrays example
+12.3k Golang : 2 dimensional array example
+7.3k Golang : Calculate how many weeks left to go in a given year
+30.6k Golang : Remove characters from string example
+5.8k Linux : Disable and enable IPv4 forwarding
+13.9k Golang : How to determine if a year is leap year?
+10.5k Swift : Convert (cast) String to Integer
+13.8k Golang : unknown escape sequence error
+9k Golang : Populate or initialize struct with values example
+8.7k Golang : How to join strings?