×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.Contains() Function with Examples

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

bytes.Contains()

The Contains() function is an inbuilt function of the bytes package which is used to check whether the given byte subslice is within byte slice b.

It accepts two parameters (b, subslice []byte) and returns true if subslice is within b; false, otherwise.

Syntax

func Contains(b, subslice []byte) bool

Parameters

  • b : The main byte slice in which we have to check the subslice.
  • subslice : The byte slice to be checked within the byte slice b.

Return Value

The return type of the bytes.Contains() function is a bool, it returns true if subslice is within b; false, otherwise.

Example 1

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Declaring byte slices
	var a = []byte{100, 200, 10, 20, 30, 40, 50}
	var b = []byte{10, 20, 30}
	var c = []byte{10, 20, 30, 70, 120, 255}

	// Checking whether subslice is within the slice
	fmt.Println(bytes.Contains(a, b))
	fmt.Println(bytes.Contains(a, c))
	fmt.Println(bytes.Contains(c, b))
}

Output:

true
false
true

Example 2

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Println(bytes.Contains(
		[]byte("Hello, world!"), []byte("Hello")))
	fmt.Println(bytes.Contains(
		[]byte("Hello, world!"), []byte("world!")))
	fmt.Println(bytes.Contains(
		[]byte("Hello, world!"), []byte("Hi!")))
	fmt.Println(bytes.Contains(
		[]byte("Hello, world!"), []byte(", w")))
}

Output:

true
true
false
true

Example 3:

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Declaring byte slices
	var a = []byte{100, 200, 10, 20, 30, 40, 50}
	var b = []byte{10, 20, 30}
	var c = []byte{10, 20, 30, 70, 120, 255}

	// Checking whether subslice is within the slice
	result := bytes.Contains(a, b)
	if result == true {
		fmt.Printf("%t, a contains b\n", result)
	} else {
		fmt.Printf("%t, a does not contain b\n", result)
	}

	result = bytes.Contains(b, c)
	if result == true {
		fmt.Printf("%t, b contains c\n", result)
	} else {
		fmt.Printf("%t, b does not contain c\n", result)
	}

	result = bytes.Contains(c, b)
	if result == true {
		fmt.Printf("%t, c contains b\n", result)
	} else {
		fmt.Printf("%t, c does not contain b\n", result)
	}
}

Output:

true, a contains b
false, b does not contain c
true, c contains b

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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