如何获取字符串.Contains中的结果数量?

huangapple go评论91阅读模式
英文:

How to get number of results in strings.Contains?

问题

当你想要检查一个字符串是否包含某个子字符串时,可以按照以下方式进行:

msg := "Lorem ipsum example of lorem ipsum."
count := strings.Count(msg, "ipsum")
fmt.Println("The word 'ipsum' appears", count, "times in msg.")

这样你就可以找出单词"ipsum"在 msg 中出现的次数了。

英文:

When you want to check if a string contains some substring, you do it this way:

msg = "Lorem ipsum example of lorem ipsum."
if strings.Contains(msg, "ipsum") {
   fmt.Println("contains word ipsum")
}

How can I find out how many times the word "ipsum" appears in msg?

答案1

得分: 9

使用strings.Count(string, substring)函数可以计算字符串中非重叠的子字符串出现的次数。

以你的例子为例:

msg := "Lorem ipsum example of lorem ipsum."
fmt.Printf("包含 %d 个 ipsum", strings.Count(msg, "ipsum"))

更多信息可以参考这里

英文:

Use

> strings.Count(string, substring)

Count counts the number of non-overlapping instances of substring in string.

To use your example:

msg := "Lorem ipsum example of lorem ipsum."
fmt.Printf("contains %d occurences of ipsum", strings.Count(msg, "ipsum"))

huangapple
  • 本文由 发表于 2014年1月29日 06:09:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/21417987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定