×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.Count() Function with Examples

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

bytes.Count()

The Count() function is an inbuilt function of the bytes package which is used to count the number of non-overlapping instances of the given byte slice sep in the byte slice s.

It accepts two parameters (s, sep []byte)) and returns the total number of non-overlapping instances of sep in s.

Syntax

func Count(s, sep []byte) int

Parameters

  • s : The main byte slice in which we have to count the occurrences of byte slice sep.
  • sep : The byte slice whose occurrences is to be counted in the byte slice s.

Return Value

The return type of the bytes.Count() function is an int, it returns the total number of non-overlapping instances of sep in s.

Example 1

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Declaring byte slices
	var a = []byte{65, 66, 67, 65, 66, 67, 70}

	// Checking whether rune is within []byte
	fmt.Println(bytes.Count(a, []byte("ABC")))
	fmt.Println(bytes.Count(a, []byte("E")))
	fmt.Println(bytes.Count(a, []byte("A")))
	fmt.Println(bytes.Count(a, []byte{65, 66}))
	fmt.Println(bytes.Count(a, []byte("X")))
}

Output:

2
0
2
2
0

Example 2

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

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Println(bytes.Count(
		[]byte("Hello, world!"), []byte("H")))
	fmt.Println(bytes.Count(
		[]byte("Hello, world!"), []byte("o")))
	fmt.Println(bytes.Count(
		[]byte("Hello, world!"), []byte("l")))
	fmt.Println(bytes.Count(
		[]byte("Hello, world!"), []byte("Hello")))
	fmt.Println(bytes.Count(
		[]byte("Hello, world!"), []byte("Hi")))
}

Output:

1
2
3
1
0

Golang bytes Package »




Comments and Discussions!

Load comments ↻





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