FoldFence
FoldFence

Reputation: 2802

How do i search in a String for a multiple word

I have a string like "UUDUUUUUUUUDU" and i want to find if the string has multiple UUDU in it. It is for a permutation programm. I tried with a matcher but the matcher reacts by a single UUDU and a multiple

    Matcher matcher = Pattern.compile("UUDU|UUDU").matcher(uudu);
    if(matcher.find())
    {  

Upvotes: 2

Views: 74

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53525

You can use group matching, pay attention - the if should be replaced with a while:

String uudu = "UUDUUUUUUUUDU";
Matcher matcher = Pattern.compile("(UUDU)").matcher(uudu);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

OUTPUT

UUDU
UUDU

In order to count overlapping sub-strings, we can do:

public static int countOverlappingSubstr(String subStr, String str, int i, int count){
    int subLen =  subStr.length();
    if (i >= str.length() - subLen + 1)
        return count;
    if (str.substring(i, i + subLen).equals(subStr))
        count++;
    return countOverlappingSubstr(subStr, str, i+1, count);
}

public static void main(String[] args){
    System.out.println(countOverlappingSubstr("UUDU", "UUDUUDU", 0, 0));
}

Upvotes: 2

Dici
Dici

Reputation: 25950

If you ever need to take overlapping matches into account, here is one solution. Otherwise, use alfasin solution, which is more straightforward.

private static int countOverlappingMatches(String str, String pattern) {
    int count  = 0;
    int offset = 0;
    while (str.length() > 0) {
        int i = str.indexOf(pattern,offset);
        if (i == -1) break;
        count++;
        offset = i + 1;
    }
    return count;
}

Upvotes: 1

Evan Williams
Evan Williams

Reputation: 406

If you don't mind using an external library, the Apache Commons StringUtils class provides the method CountMatches which does exactly what you want.

Upvotes: 2

Related Questions