public class Test {
public static void main(String[] args) {
String str = "WELCOMEWELCOME";
// find the occurance of 'CO' in the given string using stream API
}
}
CodePudding user response:
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
CodePudding user response:
Use HashMap and String's API ,substring