首页 > 解决方案 > IndexOF 没有错,但我 :)

问题描述

我需要帮助:
我正在制作一个可以从 html 中读出特定字符串的程序。
我的代码:

String html = client.request(URL);
// is more or less = [html]<meta itemProp="name" content="[my target]"/> [html]

String searchString = "<meta itemProp=\"name\" content=\"";
String searchEndString = "\"/>";

while (true) {

        int from = html.indexOf(searchString);  
        if (from == -1) {
            break;
        }
        String temp = html.substring(from);
        int to = temp.indexOf(searchEndString, from);     //this is somehow -1
        String name = temp.substring(searchString.length(), to);
        // DO sth with name
        html = temp.substring(to);  
    }

例外:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:
第 45 行 java.lang.String.substring(Unknown Source) 处的 -32

String name = temp.substring(searchString.length(), to);抛出异常,因为在to那个-1时候。

为什么会int to = temp.indexOf(searchEndString, from);导致-1

我已经尝试了一个自定义html字符串,它有效。

提前致谢 :)

标签: javastringindexof

解决方案


推荐阅读