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
+9.9k Golang : Turn string or text file into slice example
+19.5k Golang : Example for DSA(Digital Signature Algorithm) package functions
+15k Golang : How do I get the local IP (non-loopback) address ?
+5.3k Javascript : Shuffle or randomize array example
+16.9k Golang : Read integer from file into array
+87.8k Golang : How to convert character to ASCII and back
+15.6k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+14k Golang : concatenate(combine) strings
+6.8k Golang : Join lines with certain suffix symbol example
+9.4k Golang : Web(Javascript) to server-side websocket example
+7.5k Golang : Gorrila set route name and get the current route name