文字列の先頭からのみ非英数字文字を置き換えようとしています。私は次のコードを思いついた:
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();
}
}
IndexOutOfBoundsExceptionはどこから来ていますか?それは可能ではないはずです:
例えば
String filter = "! "
!Character.isLettorDigit(phrase.codePointAt(0) --> true
phrase.length() > 1 --> true
phrase = phrase.replaceFirst(
Pattern.quote(phrase.substring(0, 0 + 1)), "");
phrase
今" "
、count
1
!Character.isLettorDigit(phrase.codePointAt(1) --> true
phrase.length() > 2 --> false
したがって、例外が発生する前にループが中断する必要があります。
ヒントはありますか?