我试图仅从字符串的开头替换非字母数字字符。我想出了以下代码:
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
所以循环应该在异常发生之前中断。
有什么提示吗?