Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to count specific characters present in the slice in Golang?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.
In the Go slice of bytes, you can count the elements present in it with the help of Count function. This function returns the total number of elements or the total number of some specified element available in the given slice. This function is defined under the bytes package so, you have to import bytes package in your program for accessing Count function.

Syntax:

func Count(slice_1, sep_slice []byte) int

If the sep_slice is empty slice, then this function returns 1 + the number of UTF-8-encoded code points present in the slice_1.

Example:




// Go program to illustrate how to
// count the elements of the slice
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and initializing 
    // slices of bytes
    // Using shorthand declaration
    slice_1 := []byte{'A', 'N', 'M',
            'A', 'P', 'A', 'A', 'W'}
      
    slice_2 := []byte{'g', 'e', 'e', 'k', 's'}
  
    // Counting elements in the given slices
    // Using Count function
    res1 := bytes.Count(slice_1, []byte{'A'})
    res2 := bytes.Count(slice_2, []byte{'e'})
    res3 := bytes.Count([]byte("GeeksforGeeks"), []byte("ks"))
    res4 := bytes.Count([]byte("Geeks"), []byte(""))
    res5 := bytes.Count(slice_1, []byte(""))
  
    // Displaying results
    fmt.Println("Result 1:", res1)
    fmt.Println("Result 2:", res2)
    fmt.Println("Result 3:", res3)
    fmt.Println("Result 4:", res4)
    fmt.Println("Result 5:", res5)
  
}


Output:

Result 1: 4
Result 2: 2
Result 3: 2
Result 4: 6
Result 5: 9

My Personal Notes arrow_drop_up
Last Updated : 26 Aug, 2019
Like Article
Save Article
Similar Reads