Given a string and a sub-string, the task is to get the count of overlapping substring from the given string.
Note that in Python, the
count() function returns the number of substrings in a given string, but it does not give correct results when two occurrences of the substring overlap. Consider this example –
The output we got here is 2, but the expected output is 3 since we also wanted to count the occurrence of overlapped sub-string.
In order to solve this problem, we can use
find() function in Python. It returns the start position of the first occurrence of substring in the given string, then we increment this position by 1 and continue the search from that position till the end of the string.
Below is the implementation –
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python | Merge overlapping part of lists
- Python | Find overlapping tuples from list
- Python - Non-overlapping Random Ranges
- Python - Convert Matrix to overlapping Tuple Pairs
- Python - Non-Overlapping occurrences of N Repeated K character
- Python program for sum of consecutive numbers with overlapping in lists
- Python program to find Indices of Overlapping Substrings
- Python | Ways to count number of substring in string
- Python - Count Strings with substring String List
- Python - Possible Substring count from String
- Python | Check if a Substring is Present in a Given String
- Python | Get the string after occurrence of given substring
- Python | Get the substring from given string using list slicing
- Python | Remove the given substring from end of string
- Python | Frequency of substring in given string
- Python - Filter the List of String whose index in second List contaons the given Substring
- Python | Check if substring present in string
- Python | All occurrences of substring in string
- Python | Ways to find nth occurrence of substring in a string
- Python | Substring removal in String list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : prituladima