×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.SplitAfter() Function with Examples

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

bytes.SplitAfter()

The SplitAfter() function is an inbuilt function of the bytes package which is used to slice the byte slice (s) into all subslices after each instance of sep and returns a slice of those subslices.

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

Note:

  • If the separator sep is empty, SplitAfter() splits after each UTF-8 sequence. It is equivalent to SplitAfterN() function with a count of -1.

Syntax

func SplitAfter(s, sep []byte) [][]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.

Return Value

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

Example 1

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

package main

import (
	"bytes"
	"fmt"
)

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

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

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

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.SplitAfter() 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.SplitAfter([]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.SplitAfter([]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.