Home »
Golang »
Golang Reference
Golang bytes.SplitAfterN() Function with Examples
Golang | bytes.SplitAfterN() Function: Here, we are going to learn about the SplitAfterN() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 25, 2021
bytes.SplitAfterN()
The SplitAfterN() function is an inbuilt function of the bytes package which is used to slice the byte slice (s) into subslices after each instance of sep and returns a slice of those subslices.
It accepts three parameters (s, sep []byte, n int) and returns a slice of those subslices.
Note:
- If the separator (sep) is empty, SplitAfterN() splits after each UTF-8 sequence. The count 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
Syntax
func SplitAfterN(s, sep []byte, n int) [][]byte
Parameters
- s : The main byte slice whose slices (after each instance of sep) are to be found.
- sep : The separator value to separate the slices of s.
- n : The value which is used to get the slices at most n subslices.
Return Value
The return type of the bytes.SplitAfterN() function is a [][]byte, it returns a slice of those subslices.
Example 1
// Golang program to demonstrate the
// example of bytes.SplitAfterN() function
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Printf("%q\n", bytes.SplitAfterN(
[]byte("Alone, alone, all all alone"),
[]byte(" "),
1))
fmt.Printf("%q\n", bytes.SplitAfterN(
[]byte("Alone, alone, all all alone"),
[]byte(","),
2))
fmt.Printf("%q\n", bytes.SplitAfterN(
[]byte("Alone, alone, all all alone"),
[]byte("all "),
3))
}
Output:
["Alone, alone, all all alone"]
["Alone," " alone, all all alone"]
["Alone, alone, all " "all " "alone"]
Example 2
// Golang program to demonstrate the
// example of bytes.SplitAfterN() function
package main
import (
"bytes"
"fmt"
)
func main() {
var str string
var sep string
var n int
var result [][]byte
str = "Alone, alone, all all alone"
sep = " "
n = 1
result = bytes.SplitAfterN([]byte(str), []byte(sep), n)
fmt.Printf("str: %q\n", str)
fmt.Printf("sep: %q\n", sep)
fmt.Printf("result: %q\n", result)
fmt.Println()
sep = ", "
n = 2
result = bytes.SplitAfterN([]byte(str), []byte(sep), n)
fmt.Printf("str: %q\n", str)
fmt.Printf("sep: %q\n", sep)
fmt.Printf("result: %q\n", result)
}
Output:
str: "Alone, alone, all all alone"
sep: " "
result: ["Alone, alone, all all alone"]
str: "Alone, alone, all all alone"
sep: ", "
result: ["Alone, " "alone, all all alone"]
Golang bytes Package »