思路:从s1的第0位开始切片len(s2)个字符串进行比较,相同则计数加1,依次后移,直到最后.
def search_substr(s1, s2): if len(s2) > len(s1): return 0 cnt = 0 for i in range(len(s1)): print(i) tmp = s1[i:i+len(s2)] print(tmp) if s2 in tmp: cnt += 1 return cnt print(search_substr("dabcddabc","abc"))
输出:
0 dab 1 abc 2 bcd 3 cdd 4 dda 5 dab 6 abc 7 bc 8 c 2