簡體   English   中英

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

[英]How To Find The Repeated occurrence of substring in String Using Java Stream API

public class Test {    
    public static void main(String[] args) {
       String str = "WELCOMEWELCOME";
       // find the occurance of 'CO' in the given string using stream API
    }
}

您可以使用如下所示的Stream API 和 RegEx 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

在線演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM