This program is to count the number of sub-strings in a string.
Test case:
string ABCDCDC
pattern CDC
The answer should be 2
but I am getting 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
At the end of the for j in range(0,len(sub_string))
loop j
can be at most len(sub_string)-1
(if you don't break early). So if j==len(sub_string):
is always False
. You want if j==len(sub_string)-1:
or simply else:
(meaning you've reached the end of the for
loop) instead.
Also count = 0
should be initialized at the start, not in the first for
loop:
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
Strings are sequences of 1-character substrings in Python, so you can use the built-in count()
method — in other words, you don't have to re-invent the wheel and write your own function to do it.
test_string = 'ABCDCDC'
sub_string = 'CDC'
print(test_string.count(sub_string)) # -> 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.