|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这是小甲鱼的答案:
- def findStr(desStr, subStr):
- count = 0
- length = len(desStr)
- if subStr not in desStr:
- print('在目标字符串中未找到字符串!')
- else:
- for each1 in range(length-1): # 没理解这里的意思
- if desStr[each1] == subStr[0]: # 还有这里
- if desStr[each1+1] == subStr[1]:
- count += 1
-
- print('子字符串在目标字符串中共出现 %d 次' % count)
- desStr = input('请输入目标字符串:')
- subStr = input('请输入子字符串(两个字符):')
- findStr(desStr, subStr)
复制代码
问题在代码注释里,谢谢各位大佬了!
- def findStr(desStr, subStr):
- count = 0
- length = len(desStr)
- if subStr not in desStr:
- print('在目标字符串中未找到字符串!')
- else:
- for each1 in range(length-1): # 就是为了给下面的语句提供索引值,从0开始一直到结束
- if desStr[each1] == subStr[0]: #就是把目标字符串的每一个字符取出来跟子串第一个字符比较,如果相同,在把当前索引值+1,跟子串第2个字符比,如果都相同,说明目标字符串含有子串,所以count+1
- if desStr[each1+1] == subStr[1]:
- count += 1
-
- print('子字符串在目标字符串中共出现 %d 次' % count)
- desStr = input('请输入目标字符串:')
- subStr = input('请输入子字符串(两个字符):') # 仅适用于两个字符的子串
- findStr(desStr, subStr)
复制代码
|
|