while循环和substring()导致StringIndexOutOfBoundsException

时间:2012-10-17 22:31:01

标签: java string while-loop

我正在尝试仅从字符串的开头替换非alpanumeric字符。我想出了以下代码:

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来自哪里?它应该是不可能的:

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现在是" "count 1

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

因此循环应该在异常发生之前中断。

任何提示?

1 个答案:

答案 0 :(得分:5)

交换while条件

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

这将导致Java在尝试从中提取字符之前检查count是否小于phrase的长度(请记住,它是0索引的)