You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改代码实现统计字符串在另一字符串中的出现总次数?

Fixing Substring Counting: Count All Occurrences Instead of Stopping at the First

Hey there! I see the issue with your current code—it's stopping as soon as it finds the first match, which is why you're getting 1 instead of 2 for "110010" and "10". Let's fix that so it counts every occurrence of the substring.

Why Your Current Code Fails

Your existing logic probably checks if the substring exists (like using in or a single find() call) and returns 1 immediately when it finds a match. This ignores any subsequent matches later in the string.

Solution 1: Loop with find() (Efficient for Long Strings)

We can use a loop to keep searching for the substring, starting right after the last match we found, until there are no more matches left. Here's how to implement this:

def count_substring(string, sub_string):
    count = 0
    start_index = 0
    sub_length = len(sub_string)
    
    while True:
        # Look for the substring starting from our current position
        match_position = string.find(sub_string, start_index)
        
        # If no more matches are found, exit the loop
        if match_position == -1:
            break
        
        # Increment the count and move the start index past this match
        count += 1
        # Use +1 instead if you want to count overlapping matches (e.g., "aaaa" → "aa" counts 3 times)
        start_index = match_position + sub_length
    
    return count

# Test with your example
print(count_substring("110010", "10"))  # Output: 2 (matches positions 1-2 and 4-5)

Solution 2: Iterate Through All Possible Positions (Simple and Readable)

If you prefer a more straightforward approach, you can loop through every possible starting index in the main string, check if the substring matches at that position, and count the hits:

def count_substring(string, sub_string):
    sub_length = len(sub_string)
    main_length = len(string)
    
    # Only check positions where the substring can fit without going out of bounds
    return sum(
        1 for i in range(main_length - sub_length + 1)
        if string[i:i+sub_length] == sub_string
    )

# Test the example
print(count_substring("110010", "10"))  # Output: 2

Key Notes

  • Non-overlapping vs. Overlapping Matches: The first solution uses start_index = match_position + sub_length to count non-overlapping matches (like your "10" example). If you need to count overlapping matches (e.g., "aaaa" with substring "aa" should return 3 instead of 2), change that line to start_index = match_position + 1.
  • Both methods work for most use cases—choose the one that fits your readability and performance needs.

内容的提问来源于stack exchange,提问作者statsguy21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:41:48