英文:
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"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论