Golang 如何计算字符串中重复的字符数
在Go语言中,字符串与其他语言如Java , C++ , Python等不同。它是一个宽度可变的字符序列,每个字符都由一个或多个使用UTF-8编码的字节表示。
在Go字符串中,你可以在Count()函数的帮助下计算一些特定的Unicode代码点或字符串中costr(重复字符)的非重叠实例的数量。这个函数返回一个值,代表给定字符串或字符串中存在的Unicode代码点的总数。它被定义在strings包下,因此,你必须在你的程序中导入strings包以访问Count函数。
语法
func Count(str, costr string) int
这里,str是原始字符串,costr是我们想要计算的字符串。如果costr的值为空,则该函数返回1 + str中的Unicode代码点的数量。
例子
// Go program to illustrate how to
// count the elements of the string
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating and initializing the strings
str1 := "Welcome to the online portal of GeeksforGeeks"
str2 := "My dog name is Dollar"
str3 := "I like to play Ludo"
// Displaying strings
fmt.Println("String 1: ", str1)
fmt.Println("String 2: ", str2)
fmt.Println("String 3: ", str3)
// Counting the elements of the strings
// Using Count() function
res1 := strings.Count(str1, "o")
res2 := strings.Count(str2, "do")
// Here, it also counts white spaces
res3 := strings.Count(str3, "")
res4 := strings.Count("GeeksforGeeks, geeks", "as")
// Displaying the result
fmt.Println("\nResult 1: ", res1)
fmt.Println("Result 2: ", res2)
fmt.Println("Result 3: ", res3)
fmt.Println("Result 4: ", res4)
}
输出
String 1: Welcome to the online portal of GeeksforGeeks
String 2: My dog name is Dollar
String 3: I like to play Ludo
Result 1: 6
Result 2: 1
Result 3: 20
Result 4: 0
极客教程