Python | Count the overlapping substring in a given string



Note that in Python the count () function returns the number of substrings in a given string, but it does not produce correct results when two occurrences of a substring overlap. Consider this example —

string = "GeeksforGeeksforGeeksforGeeks"

 

print (string.count ( "GeeksforGeeks" ))

Exit :

 2 

The output we got here is 2, but the expected result is 3 because we also wanted to count the occurrence of the overlapping substring.

To solve this problem, we can use the find () function in Python. It returns the starting position of the first occurrence of a substring in a given string, then we increment that position by 1 and continue searching from that position to the end of the string.

Below is the implementation —

def CountOccurrences (string, substring):

# Initialize counter and start at 0

count = 0

start = 0

 

# Search string before

# we`ve reached the end of this

while start & lt;  len (string):

 

# Check if a substring from

# start position to end

flag = string.find (substring, start)

 

if flag! = - 1 :

# If substring is present, move & # 39; start & # 39; in

# next position from the beginning of the substring

start = flag + 1

 

# Increase score

count + = 1

else :

# If there is no more substring

  # return count

  return count

 
Driver code

string = "GeeksforGeeksforGeeksforGeeks"

print (CountOccurrences (string, " Python.Engineering " ))

Exit :

 3