|
1鱼币
- def findStr(a, b):
- count = 0
- if b not in a:
- print('目标字符串中不包含要搜索的字符。')
- else:
- c = list(a)
- for i in c:
- if i == b[0]:
- if c[c.index(i) + 1] == b[1]:
- count = count + 1
- print(f'要搜索的字符在目标字符串中出现了{count}次')
- destination = input('请输入目标字符串:')
- finds = input('请输入要搜索的字符:')
- findStr(destination, finds)
复制代码
在小甲鱼python基础课程中18讲中,作业在字符串You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.中找im的次数,答案应该是找到3次,可是我的运行结果是6次,也就是把这句话中的“i”的次数数了一遍。
鱼油代码没有正确地处理连续字符的匹配和索引更新。
导致它重复计数字符“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”,并且在找到一次匹配后,索引会跳过整个子字符串的长度,以避免重复计算。
|
最佳答案
查看完整内容
鱼油代码没有正确地处理连续字符的匹配和索引更新。
导致它重复计数字符“i”的出现次数,而不是连续的子字符串“im”~
修改一下就好啦:
使用了字符串切片来直接比较是否存在子字符串“im”,并且在找到一次匹配后,索引会跳过整个子字符串的长度,以避免重复计算。
|