find a string hackerank code example

Example: 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

Tags:

Misc Example