Skip to main content
 首页 » 编程设计

python之计算字符串中子串的数量

2024年10月01日28shihaiming

我正在做 Python 作业,但我被困在这里。

显然,我必须编写一段代码来计算字符串中给定子字符串的数量。

我以为我做对了,然后我就卡在这里了。

def count(substr,theStr): 
    # your code here 
    num = 0 
    i = 0 
    while substr in theStr[i:]: 
        i = i + theStr.find(substr)+1 
        num = num + 1 
 
    return num 
 
substr = 'is' 
theStr = 'mississipi' 
print(count(substr,theStr)) 

如果我运行这个,我希望得到 2 作为结果,相反,我得到 3...

看,其他示例如 ana 和 banana 工作正常,但这个特定示例不断出错。我不知道我在这里做错了什么。

你能帮帮我吗。

请您参考如下方法:

在你的代码中

while substr in theStr[i:]: 

在目标字符串 theStr 上正确前进,但是

i = i + theStr.find(substr)+1 

从 theStr 开始继续寻找。

str.find方法接受可选的 start 和 end 参数来限制搜索:

str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

我们真的不需要在这里使用 in:我们可以检查 find 是否返回 -1。当我们需要使用 find 重复搜索以获取子字符串的索引时,执行 in 搜索有点浪费。

我假设您想找到重叠的匹配项,因为 str.count方法可以找到非重叠匹配项,并且由于它是用 C 实现的,因此比自己用 Python 实现它更有效。

def count(substr, theStr): 
    num = i = 0 
    while True: 
        j = theStr.find(substr, i) 
        if j == -1: 
            break 
        num += 1 
        i = j + 1 
    return num 
 
print(count('is', 'mississipi')) 
print(count('ana', 'bananana')) 

输出

2 
3 

这段代码的核心是

j = theStr.find(substr, i) 

i初始化为0,所以我们从theStr开始查找,由于i = j + 1后续查找从最后找到的匹配项之后的索引开始查找。