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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
  
}

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.