编写程序Python统计字符出现次数,不用切片

  1. 编写程序,输入字符串str1和str2,统计字符串str1在字符串str2中出现的次数。要求:计算一个字符串在另一个字符串中出现次数的功能,需要定义函数实现。函数中除了字符串的len()方法外,不能调用其他的字符串功能函数,切片也不行。
    例如:输入:abc
         *abc12ababcab
         输出:2
    

def cou(str1, str2):
    len1 = len(str1)
    len2 = len(str2)
    count = 0
    if len1 < len2:
        str1, str2 = str2, str1
    i = 0
    while i <= len1 - len2:
        j = 0
        for _ in range(len2):            
            if str1[i+j] == str2[j]:
                j += 1
        if j ==len2:
            count += 1
            i += j
        else:
            i += 1
    return count
    
res = cou('*abc12ababcab', 'abc')
print(res)