如何纠正代码返回字符串中的子串的数量? [重复]

问题描述 投票:-1回答:1

这个问题已经在这里有一个答案:

我要让程序,计算在一个给定的串子的数目。

s = 'azcbobobegghakl'
substring = "bob"

for i in range(0, len(s)):
    if substring in s:
        j = 0
        count = 0
        count1 = 0
        while s[i] == substring[j]:
            count += 1
            i += 1
            j += 1
            if j > len(substring):
                break
        if count == len(substring):
            count1 += 1
            count = 0
        else:
            i += 1

print(count1)
python
1个回答
0
投票
import re
s = 'azcbobobegghakl'
searchSub = 'bob'
print(len(re.findall('(?=' + searchSub + ')',s)))

OUTPUT:

2
© www.soinside.com 2019 - 2024. All rights reserved.