计算较大字符串中字符串的出现次数

时间:2017-07-25 15:34:26

标签: python

我希望了解如何使我的代码能够正常工作。学习这个概念可能会解释我的编程理解。我试图计算字符串'bob'出现在一个更大的字符串中的次数。这是我的方法:

s='azcbobobegghakl'

for i in range(len(s)):
    if (gt[0]+gt[1]+gt[2]) == 'bob':
       count += 1
       gt.replace(gt[0],'')
    else:
       gt.replace(gt[0],'')

print count

如何使用for i in range(len(s))来引用我的字符串而不必使用整数?

2 个答案:

答案 0 :(得分:0)

试试这个:

def number_of_occurrences(needle, haystack, overlap=False):
    hlen, nlen = len(haystack), len(needle)

    if nlen > hlen:
        return 0 # definitely no occurrences

    N, i = 0, 0

    while i < hlen:
        consecutive_matching_chars = 0
        for j, ch in enumerate(needle):
            if (i + j < hlen) and (haystack[i + j] == ch):
                consecutive_matching_chars += 1
            else:
                break

        if consecutive_matching_chars == nlen: 
            N += 1

            # if you don't need overlap, skip 'nlen' characters of 'haystack'
            i += (not overlap) * nlen # booleans can be treated as numbers

        i += 1

    return N

使用示例:

haystack = 'bobobobobobobobobob'
needle = 'bob'

r = number_of_occurrences(needle, haystack)
R = haystack.count(needle)

print(r == R)

答案 1 :(得分:0)

感谢。你的支持有助于我在这里得到答案:

  numBobs = 0
  for i in range(1, len(s)-1):
      if s[i-1:i+2] == 'bob':
          numBobs += 1
  print 'Number of times bob occurs is:', numBobs
相关问题