Golang bytes.Count() Function

Golang bytes.Count() function is used to “count the number of non-overlapping instances of the provided byte slice sep in the byte slice.”

Syntax

func Count(s, sep []byte) int

Parameters

  1. s: It is the byte slice in which you want to search.
  2. sep: It is the byte slice you’re searching for.

Return value

The Count() function returns an int which is the number of non-overlapping instances of sep in s.

If sep is an empty slice, the function returns len(s) + 1.

Example 1: How to Use bytes.Count() function

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("hello world, hello universe")
  sep := []byte("hello")

  count := bytes.Count(s, sep)
  fmt.Println(count)
}

Output

2

Example 2: Counting occurrences of a single byte

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("banana")
  sep := []byte("a")

  count := bytes.Count(s, sep)
  fmt.Println(count)
}

Output

3

Example 3: Counting with an empty separator

If the separator is an empty slice, the function returns len(s) + 1. This example demonstrates this behavior.

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("apple")
  sep := []byte("")

  count := bytes.Count(s, sep)
  fmt.Println(count)
}

Output

6

That’s it!

Related posts

Golang bytes.ContainsRune()

Golang bytes.ContainsFunc()

Golang bytes.ContainsAny()

Golang bytes.Contains()

Golang bytes.Clone()

Leave a Comment