Golang 如何计算分片中存在的特定字符
在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的字节slice中,你可以在Count函数的帮助下计算其中存在的元素。这个函数返回元素的总数或者在给定的片断中可用的某些指定元素的总数。这个函数被定义在字节包下,所以你必须在你的程序中导入字节包来访问计数函数。
语法
func Count(slice_1, sep_slice []byte) int
如果sep_slice是空片,那么这个函数就会返回1+存在于slice_1中的UTF-8编码的代码点的数量。
例子
// 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)
}
输出
Result 1: 4
Result 2: 2
Result 3: 2
Result 4: 6
Result 5: 9
极客教程