这是我的问题:编写一个接受两行输入的程序,我们称第一个针和第二个干草堆。打印针作为 haystack 的子串出现的次数。鼓励我使用循环和等价运算符。
我没有取得太大进展 - 这是我 4 小时后的代码......
..两天后我得到了这个...
needle = 'sses'
haystack = 'assesses'
count = 0 # initialize the counter
index = haystack.index(needle) # get the first character in the substring
string1 = haystack[index:len(needle) + index] # get the whole substring
for position in range(0,len(haystack)): # loop through the string
if haystack[position:len(needle) + index] == string1: # match the 1st substring
count += 1 # iterate the counter
print (count)
...我的问题是,如何让 for 循环计算字符串的第二次出现?
谢谢
蒂姆
最后,“正确”的答案:
needle = input()
haystack = input()
count = 0
if needle in haystack:
index = haystack.index(needle)
string1 = haystack[index:len(needle) + index]
for position in range(0,len(haystack)):
if haystack[position:len(needle) + position] == string1:
count += 1
print (count)