×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.Split() Function with Examples

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

bytes.Split()

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

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

Syntax

func Split(s, sep []byte) [][]byte

Parameters

  • s : The main byte slice whose slices are to be found.
  • sep : The separator value to separate the slices of s.

Return Value

The return type of the bytes.Split() function is a [][]byte, it returns a slice of the subslices between those separators.

Example 1

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

package main

import (
	"bytes"
	"fmt"
)

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

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

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

Output:

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

Example 2

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str string
	var sep string
	var result [][]byte

	str = "Alone, alone, all all alone"
	sep = " "
	result = bytes.Split([]byte(str), []byte(sep))
	fmt.Printf("str: %q\n", str)
	fmt.Printf("sep %q\n", sep)
	fmt.Printf("result: %q\n", result)
	fmt.Println()

	sep = ", "
	result = bytes.Split([]byte(str), []byte(sep))
	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.