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

如何使用Java Stream API查找字符串中子串的重复出现次数

Using Java Stream API to Count Substring Occurrences

Got it, let's work through this problem together—using Java's Stream API to count how many times the substring CO shows up in the given string. Here's the complete, working solution with breakdowns:

public class Test {
    public static void main(String[] args) {
        String str = "WELCOMEWELCOME";
        String targetSubstring = "CO";
        
        // Calculate occurrences with Stream API
        long occurrenceCount = IntStream.range(0, str.length() - targetSubstring.length() + 1)
                .mapToObj(startIdx -> str.substring(startIdx, startIdx + targetSubstring.length()))
                .filter(sub -> sub.equals(targetSubstring))
                .count();
        
        System.out.printf("The substring '%s' appears %d times.%n", targetSubstring, occurrenceCount);
    }
}

Let's break down each step:

  • Generate valid start positions: We use IntStream.range to create a stream of all possible starting indices for our target substring. The upper limit str.length() - targetSubstring.length() + 1 ensures we never try to extract a substring that goes beyond the main string's bounds.
  • Extract candidate substrings: mapToObj converts each start index into a substring of the same length as CO, so we're only checking relevant chunks of the main string.
  • Filter matches: The filter operation keeps only those substrings that exactly match our target CO.
  • Count matches: Finally, count() gives us the total number of valid matches as a long.

When you run this code with the input string "WELCOMEWELCOME", the output will be:

The substring 'CO' appears 2 times.

This approach also handles edge cases smoothly—if the main string is shorter than the target substring, the stream will be empty and count() will return 0 without throwing errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:38:11