user3212766 user3212766 -4 years ago 65
Java Question

I am having trouble getting substring to work

This method is supposed to get the number of occurrences of a certain pattern and return the int value. I keep getting this error

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1


Code

public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i <= strand.length(); i++) {
if (strand.substring(i, i + pattern.length()) == pattern) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}

Answer Source

You need to correct your condition check in loop and also add new check inside loop block:

public int getCount(String pattern){
    int occerenceOfPattern = 0;
    for (int i = 0; i < strand.length(); i++) { // Updated check
        if((i + pattern.length()) >= strand.length()) // New condition to avoid exception
            break;
        if (strand.substring(i, i + pattern.length()) == pattern) {
            occerenceOfPattern++;
        }
    }
    return occerenceOfPattern;
}

New added check can also be handled in loop condition itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download