Menu Close

Go – Cut first matching bytes in slice of bytes in go

Here, bytes.Cut() function is used to cut first matching bytes in slice of bytes in go. Cut() function returns slices of the original slice.

Cut() built-in function of bytes package slices bytes around the first instance of separator. It returns the text before and after separator.

bytes.Cut() function prototype:

func Cut(s, sep []byte) (before, after []byte, found bool)

Input parameters:
s: slice of bytes
sep: Slice of bytes to be cut first instance of separator in s

Return:
before: text before separator
after: text after separator
found: true if separator is present in s else false

Explanation:

1)
s := []byte("yes Techie hello Techie hi Techie")
sep := []byte("Techie")

Output:
before: yes
after: "hello Techie hi Techie"
found: true

2)
s := []byte("yes Techie hello Techie hi Techie")
sep := []byte("good")

Output:
before: "yes Techie hello Techie hi Techie"
after: ""
found: false

Example:

Code 1:

package main

import (
	"bytes"
	"fmt"
)

func main() {

	x := []byte("yes Techie hello Techie hi Techie")

	before, after, found := bytes.Cut(x, []byte("Techie"))

	fmt.Printf("%q, %q, %v", before, after, found)
	

	x = []byte("yes Techie hello Techie hi Techie")

	before, after, found = bytes.Cut(x, []byte("Good"))

	fmt.Printf("\n%q, %q, %v", before, after, found)
}

Output:

% go run sample.go

"yes ", " hello Techie hi Techie", true
"yes Techie hello Techie hi Techie", "", false%     

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published.

Contact Us