Golang bytes.SplitN() function example
bytes package
SplitN slices the input slice into subslices separated by separator(2nd parameter) and returns a slice of the subslices between those separators. If separator is empty, SplitN 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.SplitN() function usage example
package main
import (
"fmt"
"bytes"
)
func main() {
str := []byte("I LOVE THIS WORLD!")
for i, rune := range bytes.SplitN(str, []byte{' '}, 2) {
fmt.Printf("Counter %d : %s\n", i , string(rune))
}
fmt.Println("--------------")
for i, rune := range bytes.SplitN(str, []byte{' '}, 3) {
fmt.Printf("Counter %d : %s\n", i , string(rune))
}
fmt.Println("--------------")
for i, rune := range bytes.SplitN(str, []byte{' '}, 4) {
fmt.Printf("Counter %d : %s\n", i , string(rune))
}
fmt.Println("--------------")
for i, rune := range bytes.SplitN(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
+8.5k Android Studio : Import third-party library or package into Gradle Scripts
+18.5k Golang : Send email with attachment
+15.3k nginx: [emerg] unknown directive "ssl"
+15.6k Golang : Get checkbox or extract multipart form data value example
+21.4k Curl usage examples with Golang
+5.8k Linux : Disable and enable IPv4 forwarding
+9.4k Golang : Play .WAV file from command line
+4.7k MariaDB/MySQL : Form select statement or search query with Chinese characters
+18.5k Golang : Set, Get and List environment variables
+5.6k Javascript : How to refresh page with JQuery ?
+11.8k Golang : Verify Linux user password again before executing a program example
+52.6k Golang : How to get struct field and value by name