find a string hackereank 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

Here is what the above code is Doing:
1. It is taking the string and substring as input
2. It is initialising a count variable to 0
3. It is traversing the string from left to right and looking for the occurence of substring
4. If it finds the substring, it will increase the count by 1
5. It will return the count

Similar Posts