英文:
Is there a Count function in Go but for overlapping substrings?
问题
我正在使用Go语言的strings.Count(s, subtring)
函数,它工作得很好,但它只能找到字符串s
中的非重叠的子字符串实例。是否有一个函数可以找到重叠的实例呢?
例如:
s := "ccc"
fmt.Println(strings.Count(s, "cc")) // 返回1,但我想要2(有两个子字符串s[0:1]和s[1:2])
谢谢。
英文:
Im using Go's strings.Count(s, subtring)
function which works fine but it finds only the non-overlapping instances of subtring in s
. Is there a function which finds the overlapping instances as well?
So for example
s := "ccc"
fmt.Println(strings.Count(s, "cc")) // returns 1 but I want 2 (there are 2 substrings s[0:1] and s[1:2])
Thanks
答案1
得分: 3
这似乎可以实现:
package main
import "strings"
func count(sub, pat string) int {
var c int
for d := range sub {
if strings.HasPrefix(sub[d:], pat) { c++ }
}
return c
}
func main() {
c := count("ccc", "cc")
println(c == 2)
}
请注意,如果Go语言有正则表达式的前瞻功能,你可以像Python一样做:
>>> import re
>>> len(re.findall('(?=cc)', 'ccc'))
2
英文:
This seems to do it:
package main
import "strings"
func count(sub, pat string) int {
var c int
for d := range sub {
if strings.HasPrefix(sub[d:], pat) { c++ }
}
return c
}
func main() {
c := count("ccc", "cc")
println(c == 2)
}
Note if Go had Regular Expression Lookahead, you could do something like this
Python:
>>> import re
>>> len(re.findall('(?=cc)', 'ccc'))
2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论