Number of occurrences of a substring in a string

前端 未结 6 1563
死守一世寂寞
死守一世寂寞 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 05:06

    When you do s.find('bob') you search from the beginning, so you end-up finding the same bob again and again, you need to change your search position to end of the bob you found.

    string.find takes start argument which you can pass to tell it from where to start searching, string.find also return the position are which it found bob, so you can use that, add length of bob to it and pass it to next s.find.

    So at start of loop set start=0 as you want to search from start, inside loop if find returns a non-negative number you should add length of search string to it to get new start:

    srch = 'bob'
    start = numBobs = 0 while start >= 0:
        pos = s.find(srch, start)
        if pos < 0:
          break
        numBobs += 1
        start = pos + len(srch)
    

    Here I am assuming that overlapped search string are not considered

提交回复
热议问题