一般实现方法:
# -*- coding:'utf-8' -*-
A = input("请输入长字符串:")
B = input("请输入子字符串:")
p = A.count(B)
print(p)
def str_count(a,b):
'''
计算子字符串个数
'''
length_a = len(a)
length_b = len(b)
count = 0
i = 0
for j in range(length_a):
if a[j] == b[i]:
if i == length_b-1:
count = count+1
i = 0
else:
i += 1
if j<(length_a-1) and a[j+1] != b[i]:
i = 0
else:
continue
return count
if __name__=='__main__':
str_count(A,B)
print(str_count(A,B))
为了显得更加实用和方便,使用类函数封装再实现:
# -*- coding:'utf-8' -*-
# A = input("请输入长字符串:")
# p = A.count(B)
# print(p)
class Str:
def __init__(self,str):
self.str = str
def str_count(self,substr):
'''
计算子字符串个数
'''
length_a = len(self.str)
length_b = len(substr)
count = 0
i = 0
for j in range(length_a):
if self.str[j] == substr[i]:
if i == length_b-1:
count = count+1
i = 0
else:
i += 1
if j<(length_a-1) and self.str[j+1] != substr[i]:
i = 0
else:
continue
return count
try:
route = input("请输入文件路径:")
fp = open(route,'r+')
except:
print("文件不存在!")
else:
print("打开文件成功")
def main():
B = input("请输入要查找的字符串:")
A = fp.read()
str = Str(A)
str.str_count(B)
print("文中含有%d个%s" % (str.str_count(B),B))
fp.close()
if __name__=='__main__':
main()