2 回答

TA貢獻1856條經驗 獲得超11個贊
您可以使用count
print("hellohel".count("hel"))
2
如果你想計算重疊的發生次數......也許這可以幫助
def countOverlapping(string, item):
? ? count = 0
? ? for i in range(0,len(string)):
? ? ? ? if item in string[i:len(item)+i]:
? ? ? ? ? ? count += 1
? ? return count
print(countOverlapping("ehehe", "ehe"))
輸出應該是...
2
這是如何運作的?
它使用了他所謂的滑動窗口方法
我們獲取子字符串的長度,并在每次迭代時檢查它是否在字符串的“窗口”中:
is ehe in [ehe]he? yes, count += 1
is ehe in e[heh]e? no, pass
is ehe in eh[ehe]? yes, count += 1

TA貢獻1825條經驗 獲得超4個贊
您需要采用滑動窗口方法來獲取字符串中子字符串的計數。
例子:
字符串:“嘿嘿嘿”
子串:“呃”
從前 3 個(因為子字符串的長度為 3)字母“ehe”開始 - 這是我們要查找的子字符串嗎?- 是的。
現在留下第一個字母“e”并將字母“he”與下一個字母“h”組合起來形成“heh”,這是我們要尋找的子字符串嗎?- 不
現在留下第一個字母“h”并將字母“eh”與下一個字母“e”組合起來形成“ehe”,這是我們正在尋找的子字符串嗎?是的
執行到字符串末尾并計算“yes”的數量
添加回答
舉報