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
+22.7k Golang : Strings to lowercase and uppercase example
+62.7k Golang : Convert HTTP Response body to string
+7.9k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+10.1k Golang : Get login name from environment and prompt for password
+7.8k Golang : Regular Expression find string example
+6.7k Golang : When to use make or new?
+5.3k Golang : Get FX sentiment from website example
+5.5k Golang : If else example and common mistake
+29.5k Golang : Login(Authenticate) with Facebook example
+8.8k Golang : Executing and evaluating nested loop in html template
+14.1k Golang : Check if a file exist or not