你好,我是 Java 的新手,在我的代码中我收到一个错误,因为字符串索引超出范围:-21 我的代码是
String targetLexForRemaining=categoryWordStr.substring(categoryWordStr.indexOf("@@")+2,categoryWordStr.indexOf(" "));
在这一行我得到一个错误? 我应该为此做什么?
最佳答案
IndexOutOfBoundsException如果 beginIndex
为负数,或者 endIndex
大于此 String 对象的长度,或者 beginIndex
大于 endIndex,则抛出
。读它的 documentation .
在调用 subString
方法之前,您应该检查这些条件。
int beginIndex=categoryWordStr.indexOf("@@");
int endIndex=categoryWordStr.indexOf(" ");
if(beginIndex!=-1 && beginIndex<=endIndex && endIndex<=categoryWordStr.length())
{
//Call Substring
}
关于java - 字符串索引超出范围 : -21,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17834113/