fork download
  1. class StringUtil:
  2.  
  3. def __init__(self, s):
  4. self.string = s
  5.  
  6.  
  7. def count(self,substring,start=0, end=-1): # end index/slice: -1 for the last, instead len(self.substring) - 1
  8. self.substring = substring
  9. self.start = start
  10. self.end = end
  11. self.queue = 0
  12. self.counter = 0
  13.  
  14. for a in self.string[start:]:
  15. if a == self.substring[0]:
  16. self.queue += 1
  17. if a == self.substring[end] and self.queue != 0: # -1 for the last, instead len(self.substring) - 1
  18. self.queue -= 1
  19. self.counter += 1
  20.  
  21. return self.counter
  22.  
  23.  
  24. sub = "o*o"
  25. s = "Hell" + sub + " W" + sub + "rld"
  26. cnt = StringUtil(s).count(sub)
  27. print(f" counted '{sub}' in '{s}' times: {cnt}")
Success #stdin #stdout 0.02s 9204KB
stdin
Standard input is empty
stdout
 counted 'o*o' in 'Hello*o Wo*orld' times: 4