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

问题描述 投票:0回答:1
public class Test {    
    public static void main(String[] args) {
       String str = "WELCOMEWELCOME";
       // find the occurance of 'CO' in the given string using stream API
    }
}
java string java-stream substring frequency
1个回答
6
投票

您可以使用如下所示的流和正则表达式 API 来满足此要求:

import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class Main {
    public static void main(String args[]) {
        // find the occurance of 'CO' in the given string using stream API
        String str = "WELCOMEWELCOME";
        String substring = "CO";
        
        System.out.println(getSubstringCount(str, substring));
    }
    static long getSubstringCount(String str, String substring) {
        return Pattern.compile(substring)
                .matcher(str)
                .results()
                .map(MatchResult::group)
                .count();
    }
}

输出:

2

在线演示

© www.soinside.com 2019 - 2024. All rights reserved.