Python如何计算给定字符串中的重叠子字符串?——已解决

给定一个字符串和一个子字符串,任务是从给定的字符串中获取重叠子字符串的计数。注意,在Python中,count()函数返回给定字符串中的子字符串数量,但是当两个子字符串出现重叠时,它不会给出正确的结果。考虑一下这个例子:

string = "SrcBinSrcBinSrcBinSrc"
  
print(string.count("SrcBinSrc")) 

这里得到的输出是2,但是预期的输出是3,因为我们还想计算重叠子字符串的出现次数。为了解决这个问题,我们可以在Python中使用find()函数。它返回给定字符串中第一个出现的子字符串的起始位置,然后将该位置增加1,并从该位置继续搜索,直到字符串结束。下面是实现代码:

def CountOccurrences(string, substring): 
    # 初始化count和start为0 
    count = 0
    start = 0
  
    # 搜索字符串直到终点
    while start < len(string): 
  
        # 检查从"start"位置到结束是否存在子字符串
        flag = string.find(substring, start) 
  
        if flag != -1: 
            # 如果存在子字符串,将"start"从子字符串的开始移动到下一个位置
            start = flag + 1
  
            # count自增 
            count += 1
        else: 
            # 如果没有其他子字符串,返回count的值
            return count 
  

string = "SrcBinSrcBinSrcBinSrc"
  
print(CountOccurrences(string, "SrcBinSrc"))

来源:

https://www.srcmini02.com/1399.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_35853.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?