字符串中子字符串出现的次数 [英] Number of occurrences of a substring in a string

查看:80
本文介绍了字符串中子字符串出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算子字符串 'bob' 在字符串中出现的次数.

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

示例问题:求'bob'在字符串s中出现的次数,使得

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

"s = xyzbobxyzbobxyzbob"  #(here there are three occurrences)

这是我的代码:

s = "xyzbobxyzbobxyzbob"

numBobs = 0

while(s.find('bob') >= 0)
   numBobs = numBobs + 1
   print numBobs

由于 Python 中的 find 函数应该在未找到子字符串时返回 -1,因此 while 循环应该在每次找到子字符串时打印出增加的 bob 数后结束.

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.

推荐答案

当你做 s.find('bob') 时,你从头开始搜索,所以你最终找到了同一个 bob一次又一次,您需要将搜索位置更改为找到的鲍勃的末尾.

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 接受 start 参数,你可以传递它来告诉它从哪里开始搜索,string.find 还返回它找到 bob 的位置,所以您可以使用它,将 bob 的长度添加到它并将其传递给下一个 s.find.

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.

所以在循环开始时设置 start=0 作为你想从头开始搜索,如果 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

这篇关于字符串中子字符串出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆