【问题标题】:How To Find The Repeated occurrence of substring in String Using Java Stream API如何使用 Java Stream API 查找字符串中重复出现的子字符串
【发布时间】:2021-11-29 03:09:46
【问题描述】:
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 stream substring frequency


    【解决方案1】:

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

    ONLINE DEMO

    【讨论】:

      猜你喜欢
      • 2017-10-23
      • 2011-04-15
      • 2021-01-11
      • 2015-12-23
      • 2014-05-09
      • 2020-02-24
      • 1970-01-01
      • 2013-04-21
      • 2012-10-18
      相关资源
      最近更新 更多