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:
// 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
Recommended Posts:
- Check if the specified element is present in the slice of bytes in Golang
- Golang | Finding Index of the Regular Expression present in Slice
- Check if the given characters is present in Golang String
- How to copy one slice into another slice in Golang?
- How to Count the Number of Repeated Characters in a Golang String?
- How to sort a slice in Golang?
- How to append a slice in Golang?
- How to sort a slice of ints in Golang?
- Golang | Splitting the slice after the specified separator
- How to pass a Slice to Function in Golang?
- How to sort a slice stable in Golang?
- How to trim a slice of bytes in Golang?
- How to Sort a Slice of Strings in Golang?
- How to split a slice of bytes in Golang?
- How to sort a slice of float64s in Golang?
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.



