Number of occurrences of a substring in a string

前端 未结 6 1541
死守一世寂寞
死守一世寂寞 2020-12-12 04:08

I need to count the nunber of times the substring \'bob\' occurs in a string.

Example problem: Find the number of times \'bob\' occurs in string s such

6条回答
  •  有刺的猬
    2020-12-12 04:45

    Here is a solution that returns number of overlapping sub-strings without using Regex: (Note: the 'while' loop here is written presuming you are looking for a 3-character sub-string i.e. 'bob')

    bobs = 0
    start = 0
    end = 3
    while end <= len(s) + 1 and start < len(s)-2 :
        if s.count('bob', start,end) == 1:
            bobs += 1
        start += 1
        end += 1
    
    print(bobs)
    

提交回复
热议问题