0

How do I count the occurrences of a substring in a string if they overlap? For example: I want to count how many single Os are there in the string:

string = 'xooxxoxoxoooxxoxoxxoxxxooxox'
string.count('xox')

This way, it gives only 4, because where there is 'xoxox', it only counts once. How can I make it work?

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
Tamas Koos
  • 1,053
  • 3
  • 15
  • 35
  • Have you tried doing your own algorithm? make a loop over the string characters and if it's an 'o' check if the previous and the next characters are not 'o's then add 1 to your counter. – multivac Oct 03 '15 at 17:06
  • I've made you a script [here](http://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences/32925627#32925627) – Shapi Oct 03 '15 at 17:53

0 Answers0