Is there a Count function in Go but for overlapping substrings?

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

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

huangapple
  • 本文由 发表于 2021年6月13日 17:59:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/67956996.html
匿名

发表评论

匿名网友

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

确定