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
+4.7k Golang : How to pass data between controllers with JSON Web Token
+18.5k Golang : Aligning strings to right, left and center with fill example
+15.9k Golang : Get current time from the Internet time server(ntp) example
+15.7k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+6.8k Golang : Calculate pivot points for a cross
+11.1k Golang : How to determine a prime number?
+15.6k Golang : ROT47 (Caesar cipher by 47 characters) example
+6.7k Golang : When to use make or new?
+14k Golang : Compress and decompress file with compress/flate example
+16.6k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+29.5k Golang : Saving(serializing) and reading file with GOB
+4.6k JavaScript : Rounding number to decimal formats to display currency