Go语言字符串出现次数

Go语言字符串出现次数教程

在开发过程中,很多时候我们有统计 单个字符 或者 字符串 在另一个字符串中出现次数的需求,在 Go 语言 中,统计字符串出现次数我们使用 count() 函数。

Strings.count()函数

语法

func Count(s, substr string) int

参数

参数 描述
s 表示原字符串。
substr 表示要检索的字符串。

返回值

函数返回 int 类型的值,如果检索的字符串不存在,则返回 0,否则返回出现的次数。

案例

单个字符出现次数

使用 Strings.count() 函数,统计字符串中单个字符出现的次数

package main import ( "fmt" "strings" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用 Strings.count() 函数,统计字符串中单个字符出现的次数 strHaiCoder := "Study Golang From HaiCoder" count := strings.Count(strHaiCoder, "o") fmt.Println("count =", count) }

程序运行后,控制台输出如下:

17 golang统计字符串出现次数.png

首先,我们定义了一个字符串类型的 变量 strHaicoder,接着我们使用字符串的 Strings.count() 函数统计字符串变量 strHaicoder 中单个字符 o 出现的次数,并使用 print() 函数,打印最终的结果。

字符 o 在变量 strHaicoder 中一共出现了三次,因此最终打印了 3。

字符串出现次数

使用 Strings.count() 函数,统计字符串中指定字符串出现的次数

package main import ( "fmt" "strings" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用 Strings.count() 函数,统计字符串中指定字符串出现的次数 strHaiCoder := "I love Golang and I study Golang From HaiCoder" count := strings.Count(strHaiCoder, "Golang") fmt.Println("count =", count) }

程序运行后,控制台输出如下:

18 golang统计字符串出现次数.png

首先,我们定义了一个字符串类型的变量 strHaicoder,接着我们使用字符串的 Strings.count() 函数统计字符串变量 strHaicoder 中字符串 Golang 出现的次数,并使用 print() 函数,打印最终的结果。

字符串 Golang 在变量 strHaicoder 中一共出现了两次,因此最终打印了 2。

Go语言字符串出现次数总结

在开发过程中,很多时候我们有统计单个字符或者字符串在另一个字符串中出现次数的需求,在 Go 语言 中,统计字符串出现次数我们使用 Strings.count() 函数。Go 语言 Strings.count() 函数语法:

func Count(s, substr string) int