Skip to main content
 首页 » 编程设计

python之在不使用内置函数的情况下计算子字符串的出现次数

2025年05月04日23dyllove98

我的老师要求我找到一种方法来计算单词“bob”在任何随机字符串变量中的出现次数,而无需 str.count()。所以我做到了,

a = "dfjgnsdfgnbobobeob bob" 
compteurDeBob = 0 
for i in range (len(a) - 1): 
   if a[i] == "b": 
       if a[i+1] == "o": 
           if a[i+2] == "b": 
               compteurDeBob += 1 
print(compteurDeBob) 

但我想找到一种方法来使用如下所示的任何长度的单词,但我不知道该怎么做......

a = input("random string: ") 
word = input("Wanted word: ") 
compteurDeBob = 0 
for i in range (len(a)-1): 
 
   #... i don't know...  
 
print(compteurDeBob) 

请您参考如下方法:

a = input("random string: ") 
word = input("Wanted word: ") 
 
count = 0 
for i in range(len(a)-len(word)): 
    if a[i:i+len(word)] == word: 
        count += 1 
print(count) 

如果您希望搜索不区分大小写,那么您可以使用 lower() 函数:

a = input("random string: ").lower() 
word = input("Wanted word: ").lower() 
 
count = 0 
for i in range(len(a)): 
    if a[i:i+len(word)] == word: 
        count += 1 
print(count) 

对于用户输入

Hi Bob. This is bob 

第一种方法将输出1,第二种方法将输出2