Menu Close

Go – bytes.Count() function in go

bytes.Count() function is used to count the number of non-overlapping instances in two byte slices in go.

In function bytes.Count(s, sep []byte), If sep is an empty slice, Count function will returns “1 + the number of UTF-8-encoded code points in s”.

bytes.Count() function prototype:

func Count(s, sep []byte) int

or 

func Count(s []byte, sep []byte) int

Input parameters:
s: byte slice
sep: byte slice

bytes.Count() function return value:

bytes.Count() function returns counts the number of non-overlapping instances of sep in s.

Explanation:

1)
s := []byte("techieindoor")
sep := []byte("e")
Output: 2 i.e total 2 "e" characters / bytes in "techieindoor"

2)
s := []byte("techieindoor")
sep := []byte("")
Output: 13 ,  If sep is an empty slice, Count returns "1 + the number of UTF-8-encoded code points in s".

3)
s := []byte("jubsslsyesr")
sep := []byte("s")
Output: 4 i.e total 4 "s" characters / bytes in "jubsslsyesr"

4)
b := []byte("jubssrlsyesr")
sep := []byte("sr")
Output: 2 i.e total 2 "sr" in "jubssrlsyesr"

5)
b = []byte{10, 20, 30, 40}
sep = []byte{20, 30}
Output: 1 i.e {20, 30} present only once in {10, 20, 30, 40}
	
6)
b = []byte{10, 20, 30, 40, 20, 20}
sep = []byte{20}
Output: 3 i.e {20} present 3 times in {10, 20, 30, 40, 20, 20}

Example:

package main

import (
	"bytes"
	"fmt"
)

func main() {
    b := []byte("techieindoor")
    sep := []byte("e")
	fmt.Println(bytes.Count(b, sep))
	
	b = []byte("techieindoor")
	sep = []byte("")
	fmt.Println(bytes.Count(b, sep))
	
	b = []byte("jubsslsyesr")
	sep = []byte("s")
	fmt.Println(bytes.Count(b, sep))
	
	b = []byte("jubssrlsyesr")
	sep = []byte("sr")
	fmt.Println(bytes.Count(b, sep))
	
	b = []byte{10, 20, 30, 40}
	sep = []byte{20, 30}
	fmt.Println(bytes.Count(b, sep))
	
	b = []byte{10, 20, 30, 40, 20, 20}
	sep = []byte{20}
	fmt.Println(bytes.Count(b, sep))
	
}

Output:

2
13
4
2
1
3

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