如何統計 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言學習
C++
C#
MongoDB
MySQL
Javascript
PHP