Python禁用find等函数时,如何统计子串在字符串中的出现次数?
统计子串出现次数(禁用指定内置函数)
问题描述
我刚学习Python几天,正在学习字符串与数组相关知识。我想要编写一个程序,统计子串s1在字符串s2中的出现次数。以下是我的尝试代码:
char1 = int(input("number of character of s1: ")) s1 = str(input("insert string 1: ")) char2 = int(input("number of character of s2: ")) s2 = str(input("insert string 2: ")) n = 0 bool = True start = 0 while bool: a = s2.find(s1,start) if a == -1: bool = False else: n+=1 start = a+1 print("s1 appears", n, "times in s2.")
例如,当s1为"the"、s2为"the bird the apple the chair"时,输出应为:
s1 appears 3 times in s2.
我的代码能正常运行,但现在被禁止使用find、sum、count、max、min、len、try、break等函数,我想不到替代find函数的方法,希望得到解决办法。
解决方案
既然不能用内置查找函数,我们可以利用你已经输入的s1和s2的长度,手动遍历所有可能的起始位置,逐个字符对比来判断是否匹配。
实现代码
char1 = int(input("number of character of s1: ")) s1 = input("insert string 1: ") char2 = int(input("number of character of s2: ")) s2 = input("insert string 2: ") count = 0 i = 0 loop_continue = True while loop_continue: # 检查当前起始位置是否还能容纳s1的长度 if i > char2 - char1: loop_continue = False else: is_match = True j = 0 inner_loop = True while inner_loop: if j >= char1: inner_loop = False else: # 逐个对比字符 if s1[j] != s2[i + j]: is_match = False inner_loop = False else: j += 1 if is_match: count += 1 i += 1 else: i += 1 print("s1 appears", count, "times in s2.")
代码说明
- 外层循环控制起始位置:利用输入的
char1和char2,确定s2中能容纳s1的最大起始位置是char2 - char1,当i超过这个值时停止循环。 - 内层循环对比字符:对于每个起始位置
i,逐个对比s1的第j个字符和s2的i+j位置字符,只要有一个字符不匹配,就标记为不匹配并结束内层循环。 - 计数逻辑:如果内层循环确认匹配,计数加1,然后从下一个位置继续检查(和你原代码的逻辑一致,避免遗漏重叠或连续的匹配)。
测试你提供的示例输入,这个代码会输出正确的3次结果。
内容的提问来源于stack exchange,提问作者bin07
相关产品推荐
相关产品推荐

