开发者

String Index Out Of Bounds Exception [duplicate]

This question already has an answer here: What is a StringIndexOutOfBoundsException? How can I fix it? (1 answer) Closed 5 years ago.

I am really stuck on this exception

private static void getUserComment(String s) {
    while(s.contains("author'>")){
        S开发者_运维百科ystem.out.println(s.substring(s.indexOf("author'>"),
                                       s.indexOf("<div id='")));
        s = s.substring(0, s.indexOf("author'>")) +
                           s.substring(s.indexOf("<div id='"+9));

    } 
}


You should use a proper parser or at least do some regular expression pattern matching (which is already "bad enough" for HTML or XML).

That said, your "offset" of 9 is likely the indirect cause of the exception:

s.indexOf("<div id='"+9)

This will make a literal string <div id='9 which is not found; indexOf then returns -1 and this causes the exception in the substring method. Maybe you wanted to actually add 9 to the index like this? s.indexOf("<div id='")+9

Note that the function is useless anyways, changing s will only change the local variable and not the original variable (parameters are by value in Java).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜