1. 程式人生 > >07.自定義 s.count() #規避'ccc'.count('cc')的問題

07.自定義 s.count() #規避'ccc'.count('cc')的問題

   def count_self(s,i):
        if not isinstance(s,str) and not isinstance(i,str):
            return 0
        n=len(i)
        result=0
        m=0
        while m<len(s): #while的好處是可以控制遍歷
            if s[m:m+n]==i:
                result+=1 
                m+=n #如‘ccc’.count('cc'),跳過第1位(0開始),這樣避免第1位和第2位組合
            else: 
                m+=1
        return result