【问题标题】:Got a task with String operations. matcher.find() throws outOfBoundExc, matcher.find(0) works fine... why is that?有一个字符串操作的任务。 matcher.find() 抛出 outOfBoundExc,matcher.find(0) 工作正常……这是为什么呢?
【发布时间】:2014-01-04 01:00:54
【问题描述】:

任务是从句子中删除字母 i。

public static void main(String[] args) {

    int index = 8;
    String letter = "i";
    String text = "method appends the string to the end. t is overloaded to have the following forms.";
    StringBuffer sb = new StringBuffer(text);
    Pattern pat = Pattern.compile(letter);
    Matcher mat = pat.matcher(sb);

   //while (mat.find()) -throws StringIndexOutOfBoundsException. 
    while (mat.find(0)){
        sb.deleteCharAt(mat.start());
    }

    System.out.println(sb.toString());
}

好吧,程序有效,但我不明白为什么明显的方法无效?

【问题讨论】:

    标签: java string matcher


    【解决方案1】:

    您将不得不使用mat.reset() 方法,因为当您删除字符时,匹配器知道的字符串的长度变得无效,您必须为此重置匹配器。

    发生的情况如下:您创建匹配器并将其原始长度假设为 5 的字符串传递给它,现在在调用 find 之后,您正在从缓冲区中删除一个字符,这会使匹配器的状态无效为新的长度为 4。因此需要重置。

    为什么find(0) 有效?

    答案在源头,

    JDK 1.6 中的方法,

    public boolean find(int start) {
            int limit = getTextLength();
            if ((start < 0) || (start > limit))
                throw new IndexOutOfBoundsException("Illegal start index");
    
            reset(); //reset is called here
            return search(start);
    }
    

    【讨论】:

    • 我已经提供了 find(0) 为何有效而 find() 无效的原因。
    猜你喜欢
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 2014-07-28
    相关资源
    最近更新 更多