鱼油代码没有正确地处理连续字符的匹配和索引更新。
导致它重复计数字符“i”的出现次数,而不是连续的子字符串“im”~
修改一下就好啦:
def findStr(a, b):
count = 0
length = len(b)
i = 0
while i <= len(a) - length:
# 检查从i开始的子字符串是否是我们要找的b
if a[i:i+length] == b:
count += 1
i += length # 如果找到了,跳过这个子字符串的长度
else:
i += 1 # 如果没有找到,只移动一个字符
print(f'要搜索的字符在目标字符串中出现了{count}次')
destination = "You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted."
finds = "im"
findStr(destination, finds)
使用了字符串切片来直接比较是否存在子字符串“im”,并且在找到一次匹配后,索引会跳过整个子字符串的长度,以避免重复计算。 |