0

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?

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.