如何统计 Go 语言字符串中重复字符的数目?
Count() 是 Go 语言中的内置函数,可用于统计字符串中字符/子串的不重叠实例数。
语法
func Count(s, sep string) int
其中,
s – 原始字符串
sep – 我们想要统计的子串。
它返回一个整数值。
示例
以下示例演示了如何在 Go 程序中使用 Count() 函数。
package main import ( "fmt" "strings" ) func main() { // Initializing the Strings x := "Golang Programming Language" y := "Language" // Display the Strings fmt.Println("First String:", x) fmt.Println("Second String:", y) // Using Count Function test1 := strings.Count(x, "g") test2 := strings.Count(y, "b") // Diplay the Count Output fmt.Println("Count of 'g' in the First String:", test1) fmt.Println("Count of 'b' in the Second String:", test2) }
输出
执行后,将生成以下输出 −
First String: Golang Programming Language Second String: Language Count of 'g' in the First String: 5 Count of 'b' in the Second String: 0
示例
让我们再举一个例子 −
package main import ( "fmt" "strings" ) func main() { // Initializing the Strings p := "Hyderabad" q := "Country" r := "Chennai" s := "Pune" // Display the Strings fmt.Println("First String:", p) fmt.Println("Second String:", q) fmt.Println("Third String:", r) fmt.Println("Fourth String:", s) // Using the Count Function w := strings.Count(p, "d") x := strings.Count(q, "t") y := strings.Count(r, "n") z := strings.Count(s, "e") // Display the Count Output fmt.Println("Count of 'd' in First String:", w) fmt.Println("Count of 't' in Second String:", x) fmt.Println("Count of 'n' in Third String:", y) fmt.Println("Count of 's' in Fourth String:", z) }
输出
它将生成以下输出 −
First String: Hyderabad Second String: Country Third String: Chennai Fourth String: Pune Count of 'd' in First String: 2 Count of 't' in Second String: 1 Count of 'n' in Third String: 2 Count of 's' in Fourth String: 1
广告