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
+16.9k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+12.3k Golang : How to check if a string starts or ends with certain characters or words?
+21.8k Golang : Convert string slice to struct and access with reflect example
+22.1k Golang : Join arrays or slices example
+5.8k Golang : Find change in a combination of coins example
+12.8k Golang : Listen and Serve on sub domain example
+10.6k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+20.7k Golang : Saving private and public key to files
+32.7k Golang : Regular Expression for alphanumeric and underscore
+8.2k Android Studio : Rating bar example
+29.4k Golang : JQuery AJAX post data to server and send data back to client example