findsubstring in hackerrank solution python code example
Example 1: find a string hackereank
def count_substring(string, sub_string):
count=0 #initialise count variable
for i in range(0,len(string)):
if string[i:].startswith(sub_string): # basically it traverses from left to right and looks for occurence of substring
count+=1 #every time count will increase by 1
return count
Example 2: find a string hackerrank solution
#(method 1)
import re
def count_substring(string,sub_string)
count = re.findall('(?='+sub_string+')',string)
return len(count)
# (method 2) lengthy but easier for beginners
def count_substring(string, sub_string):
zero=0
astring=string + "@"
sub_count=0
count=0
for i in range (len(astring)-1):
if astring[i]==sub_string[0]:
for j in range(1,len(sub_string)):
if astring[i+j]==sub_string[j]:
sub_count+=1
elif astring[j+i]=='@':
break
if sub_count==len(sub_string)-1:
count+=1
sub_count=0
return count