[英]How to count the number of sub-sequences in a string?
該程序用於計算字符串中子字符串的數量。
測試用例:
字符串ABCDCDC
模式CDC
答案應該是2
但我得到0
。
def count_substring(string, sub_string):
for i in range(0,len(string)-len(sub_string)+1):
count=0
for j in range(0,len(sub_string)):
if(string[i+j]!=sub_string[j]):
break;
if j==len(sub_string):
count=count+1
return count
在for j in range(0,len(sub_string))
循環中for j in range(0,len(sub_string))
的末尾, j
最多可以為len(sub_string)-1
(如果不早休息的話)。 因此, if j==len(sub_string):
始終為False
。 您想要的if j==len(sub_string)-1:
還是else:
意味着您已經到達了for
循環的末尾)。
同樣, count = 0
應該在開始而不是在第一個for
循環中初始化:
def count_substring(string, sub_string):
count=0
for i in range(0,len(string)-len(sub_string)+1):
for j in range(0,len(sub_string)):
if(string[i+j]!=sub_string[j]):
break;
else:
count=count+1
return count
字符串是Python中1個字符的子字符串的序列,因此您可以使用內置的count()
方法-換句話說,您不必重新發明輪子並編寫自己的函數即可。
test_string = 'ABCDCDC'
sub_string = 'CDC'
print(test_string.count(sub_string)) # -> 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.