Golang bytes.SplitN() Function with Examples

Golang | bytes.SplitN() Function: Here, we are going to learn about the SplitN() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 25, 2021

bytes.SplitN()

The SplitN() function is an inbuilt function of the bytes package which is used to slice the byte slice (s) into subslices separated by sep and returns a slice of the subslices between those separators.

It accepts three parameters (s, sep []byte, n int) and returns a slice of the subslices between those separators.

Note:

  • If the separator (sep) is empty, SplitN() 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 SplitN(s, sep []byte, n int) [][]byte

Parameter(s):

  • 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.SplitN() function is a [][]byte, it returns a slice of the subslices between those separators.

Example 1:

// Golang program to demonstrate the
// example of bytes.SplitN() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Printf("%q\n", bytes.SplitN(
		[]byte("Alone, alone, all all alone"),
		[]byte(" "),
		1))

	fmt.Printf("%q\n", bytes.SplitN(
		[]byte("Alone, alone, all all alone"),
		[]byte(","),
		2))

	fmt.Printf("%q\n", bytes.SplitN(
		[]byte("Alone, alone, all all alone"),
		[]byte("all "),
		3))
}

Output:

["Alone, alone, all all alone"]
["Alone" " alone, all all alone"]
["Alone, alone, " "" "alone"]

Example 2:

// Golang program to demonstrate the
// example of bytes.SplitN() 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.SplitN([]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.SplitN([]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 »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.