【问题标题】:How many times a substring appears in a string without using any count or other functions子字符串在不使用任何计数或其他函数的情况下出现在字符串中的次数
【发布时间】:2017-10-21 17:09:20
【问题描述】:

我正在尝试计算一个字符在字符串中出现的次数。例如,符号 b 在字符串 abbcddba 中出现 3 次。但是,我下面的代码会计算字符串的长度。例如,如果我尝试计算b 在字符串abbcddba 中出现的次数,则计数为8

MyStr = input('Please enter a string: ')
symb = input('Which character you want to the count for: ')
count = 0
for i in range(0,len(MyStr)):
    if symb in MyStr:
        count = count + 1
print(count)

我哪里错了?

【问题讨论】:

  • 是子串数还是字符数!?
  • 基本上,如果用户输入“apples for apples”作为字符串,然后想检查“p”在字符串中出现了多少次

标签: python


【解决方案1】:

注意:这是一种用于查找字符串中子字符串/字符计数的通用解决方案

继续检查您的符号是否存在于 Mystr 的开头,如果发现递增计数并在 MyStr 的开头剥离符号,否则跳过第一个字符并继续!

>>> MyStr = 'thisishelloheyhihello'
>>> symb = 'hello'
>>> count=0
>>> while symb in MyStr:
...     if MyStr.startswith(symbol):
...             count+=1
...             MyStr = MyStr[MyStr.find(synb,2):]
...     else:MyStr=MyStr[1:]
... 
>>> print count
2

使用 for 循环:

>>> for i in range(len(MyStr)):
...     if MyStr[i:].startswith(symb):
...             count+=1
... 
>>> count
3

【讨论】:

  • t 是从哪里来的?
  • 这似乎是解决此问题的一种非常低效的方法,因为不需要修改输入字符串。
  • 并非如此。我已经提到过了。它是通用的。
  • 如果需要维护输入字符串,只需少量修改即可!
  • 不幸的是,我需要使用 For 循环 :(
【解决方案2】:

我们可以这样去吗:

s='abbcddba'
e='b'
c=0
for a in s:
    if e==a:
        c=c+1
print(c)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2012-02-12
    • 2014-04-23
    • 2015-07-18
    相关资源
    最近更新 更多