Taha Akbari
Taha Akbari

Reputation: 224

finding the number of occurence of a substring in a string

I wanted to find the number of occurence of a substring in a string I implemented following code in java:

Pattern mypattern=Pattern.compile("a");
Matcher mymatcher=mypattern.compile("aaaaaa");
int cnt=0;
while(mymatcher.find()){
    cnt++;
)
System.out.println(cnt);

But it doesn't work when I want the function to count also the intersecting strings for example I want th e answer to the search of aa in aaaaaa be 5 but the above program will show it 3.How can I do so?

Upvotes: 0

Views: 101

Answers (3)

Nowhere Man
Nowhere Man

Reputation: 19575

A positive lookahead (?=(aa))could be used in the regular expression to handle overlapping matches:

System.out.println(Pattern.compile("(?=(aa))").matcher("aaaaaa").results().count());

// 5

Upvotes: 1

OneOfAKind_12
OneOfAKind_12

Reputation: 566

You can use Apache Commons Lang library:

System.out.println(StringUtils.countMatches(str, subStr));

Upvotes: 0

Abra
Abra

Reputation: 20924

This code will give you your desired count of 5 if you are searching for occurrences of aa in aaaaaa.

Pattern mypattern = Pattern.compile("aa");
Matcher mymatcher = mypattern.matcher("aaaaaa");
int cnt = 0;
int start = 0;
while (mymatcher.find(start)) {
    start = mymatcher.start() + 1;
    cnt++;
}
System.out.println(cnt);

Upvotes: 1

Related Questions