kei1aeh5quahQu4U
kei1aeh5quahQu4U

Reputation: 153

while loop and substring() causing StringIndexOutOfBoundsException

I'm trying to replace non-alpanumeric chars only from the beginning of a String. I came up with the following code:

public static final class FixNonAlphaNumBegin implements PhraseFilter {
    @Override
    public String filter(String phrase, long frequency) {
        int count = 0;

    while (!Character.isLetterOrDigit(phrase.codePointAt(count))
                && phrase.length() > count + 1) {
            phrase = phrase.replaceFirst(
                    Pattern.quote(phrase.substring(count, count + 1)), "");
            count++;
        }


        return phrase.trim();           
    }
}

Where are the IndexOutOfBoundsException is coming from? It should not be possible:

e.g.

String filter = "! " 

!Character.isLettorDigit(phrase.codePointAt(0) --> true 
phrase.length() > 1 --> true

phrase = phrase.replaceFirst(
                Pattern.quote(phrase.substring(0, 0 + 1)), "");

phrase is now " " , count 1

!Character.isLettorDigit(phrase.codePointAt(1) --> true 
phrase.length() > 2 --> false

So the loop should break before the exception can happen.

Any hints?

Upvotes: 0

Views: 219

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

Swap your while conditions

while (count < pharse.length() && !Character.isLetterOrDigit(phrase.codePointAt(count))) {

This will cause Java to check that the count is less then the length of the phrase (remember, it's 0 indexed) first before trying to extract the character from it

Upvotes: 5

Related Questions