我正在编写一个代码,您在其中输入一个字符串 (i) 和一个子字符串 (sb),代码应该计算子字符串在字符串中出现的次数(有重叠)。
如果您输入字符串“AAAA”并查找“A”((返回正确的数量,4),则该代码有效,但如果您输入“ADAM”并查找“A”,它将陷入无限循环。
我这辈子都解决不了这个问题。
i = input("Enter a string:")
sb = input("Enter a substring:")
count = 0
x = 0 #index from the string found
idxTotal = len(i)
while True:
i.find(sb,x)
if x != idxTotal:
count += 1
x = i.find(sb,x)+1
else:
break
print(count)
最佳答案
我认为你把事情搞得太复杂了。基本上,您应该在 while
循环中检查我们是否没有到达字符串的末尾。此外,您应该通过增加偏移值来保证进度。
所以我们可以这样写:
x = i.find(sb)
n = 0
while x >= 0:
n += 1
x = i.find(sb, x+1)
# here n is the number of occurrences
print(n)
因此,首先我们执行 i.find(sb)
来查找第一个匹配项,然后每次 将
,我们找到下一个出现的位置,因此我们递增 n
(计数)设置为零x >= 0n
,然后查找下一个出现的位置。
我们继续这样做,直到.find(..)
返回-1
。在这种情况下,while
循环将停止,n
将包含元素数量。
例如:
>>> i = 'ADAM'
>>> sb = 'A'
>>> x = i.find(sb)
>>> n = 0
>>> while x >= 0:
... n += 1
... x = i.find(sb, x+1)
...
>>> print(n)
2
这也执行重叠计数,例如:
>>> i = 'AAADAAAAAM'
>>> sb = 'AAA'
>>> x = i.find(sb)
>>> n = 0
>>> while x >= 0:
... n += 1
... x = i.find(sb, x+1)
...
>>> print(n)
4
因此,对于 'AAADAAAAAM'
,有四个与 'AAA'
的匹配项:
AAADAAAAAM
1 AAA
2 AAA
3 AAA
4 AAA
关于Python - 在字符串中查找子字符串(代码不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496604/