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 that
"s = xyzbobxyzbobxyzbob" #(here there are three occurrences)
Here is my code:
s = "xyzbobxyzbobxyzbob"
numBobs = 0
while(s.find('bob') >= 0)
numBobs = numBobs + 1
print numBobs
Since the find function in Python is supposed to return -1 if a substring is unfound the while loop ought to end after printing out the incremented number of bobs each time it finds the substring.
However the program turns out to be an infinite loop when I run it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…