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
- s: It is the byte slice in which you want to search.
- 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

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.