如何使用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.rangeto create a stream of all possible starting indices for our target substring. The upper limitstr.length() - targetSubstring.length() + 1ensures we never try to extract a substring that goes beyond the main string's bounds. - Extract candidate substrings:
mapToObjconverts each start index into a substring of the same length asCO, so we're only checking relevant chunks of the main string. - Filter matches: The
filteroperation keeps only those substrings that exactly match our targetCO. - Count matches: Finally,
count()gives us the total number of valid matches as along.
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
相关产品推荐
相关产品推荐

