2
public class Test {    
    public static void main(String[] args) {
       String str = "WELCOMEWELCOME";
       // find the occurance of 'CO' in the given string using stream API
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110

1 Answers1

5

You can use Stream API and RegEx API as shown below to meet this requirement:

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();
    }
}

Output:

2

ONLINE DEMO

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110