Golang:计算Go中字符串中一个或多个子串的出现次数?

时间:2017-03-10 19:16:08

标签: string algorithm go

我知道,为了计算一个子字符串的出现,我可以使用" strings.Count(,)"。如果我想计算substring1或substring2的出现次数该怎么办?有没有比使用strings.count()编写另一个新行更优雅的方法?

3 个答案:

答案 0 :(得分:7)

使用regular expression

https://play.golang.org/p/xMsHIYKtkQ

aORb := regexp.MustCompile("A|B")

matches := aORb.FindAllStringIndex("A B C B A", -1)
fmt.Println(len(matches))

答案 1 :(得分:0)

进行子字符串匹配的另一种方法是使用suffixarray包。以下是匹配多个模式的示例:

package main

import (
    "fmt"
    "index/suffixarray"
    "regexp"
)

func main() {
    r := regexp.MustCompile("an")
    index := suffixarray.New([]byte("banana"))
    results := index.FindAllIndex(r, -1)
    fmt.Println(len(results))
}

您还可以将单个子字符串与Lookup函数匹配。

答案 2 :(得分:0)

如果你想计算一个大字符串中匹配的数量,而不是为所有索引分配空间只是为了得到长度然后把它们扔掉,你可以在循环中使用Regexp.FindStringIndex来匹配连续的子串:

func countMatches(s string, re *regexp.Regexp) int {
    total := 0
    for start := 0; start < len(s); {
        remaining := s[start:] // slicing the string is cheap
        loc := re.FindStringIndex(remaining)
        if loc == nil {
            break
        }
        // loc[0] is the start index of the match,
        // loc[1] is the end index (exclusive)
        start += loc[1]
        total++
    }
    return total
}

func main() {
    s := "abracadabra"
    fmt.Println(countMatches(s, regexp.MustCompile(`a|b`)))
}

runnable example at Go Playground