python在一段字符串中找含有的子串个数

一般实现方法:

# -*- 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()
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值