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?
Swap your
whileconditionsThis will cause Java to check that the
countis less then the length of thephrase(remember, it’s 0 indexed) first before trying to extract the character from it