Hanwool Codes RSS Tag Admin Write Guestbook
2023-02-15 04:58:23

Find a string | HackerRank

 

Find a string | HackerRank

Find the number of occurrences of a substring in a string.

www.hackerrank.com

 

Goal

 

You have to print the number of times that the substring occurs in the given string. 

String traversal will take place from left to right, not from right to left.

 

 

Solution

 

The function starts by initializing the number variable to zero, which will be used to keep track of the count of the number of times sub_string occurs in string.

Then, it calculates the length of string and stores it in the n variable.

The function then enters a loop that will iterate n times.

In each iteration, the function uses the find method to search for the first occurrence of sub_string in the new_string variable.

If the find method returns -1, it means that sub_string is not found in new_string and the loop increments the index i by 1.

If find returns a value other than -1, it means that sub_string has been found, and the function increments the number count by 1.

The new_string is then updated to start from the position just after the found sub_string.

Finally, the function returns the number count, which is the number of times sub_string occurs in string.

 

# Find a string

def count_substring(string, sub_string):
    
    number = 0
    n = len(string)
    new_string = string
    
    for i in range(0, n):
        
        result = new_string.find(sub_string)
        
        if(result == -1):
            new_string = new_string[i:]
            i += 1
            
        else:
            new_string = new_string[result + 1:]
            i = result + 1
            number += 1
    
        
    
    
    return number

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)
Hanwool Codes. Designed by 코딩재개발.