HackerRank Python: Find a string Solution

Table of Contents

Question

Solution

				
					def count_substring(string, substring):
    count = 0
    sub_len = len(substring)
    for i in range(len(string) - sub_len + 1):
        if string[i:i+sub_len] == substring:
            count += 1
    return count

# Read the input string and substring
string = input().strip()
substring = input().strip()

# Call the count_substring function and print the result
result = count_substring(string, substring)
print(result)

				
			
  1. The function count_substring takes the string and substring as input and initializes the count variable to keep track of the number of occurrences.

  2. It calculates the length of the substring using len(substring) and then iterates over the indices of the string using the range function. The loop variable i represents the starting index of a potential substring match.

  3. Inside the loop, it checks if the substring starting at index i and ending at i+sub_len matches the given substring. If it matches, the count is incremented.

  4. Finally, the function returns the total count of substring occurrences.

  5. In the main code, the input string and substring are read from the user.

  6. The count_substring function is called with the input string and substring, and the result is stored in the result variable.

  7. The result is printed as the output.

If you find anything wrong in this Solution, feel free to reach us in the comment section.

Sharing Is Caring:

Leave a Comment