java - 字符串索引超出范围 : -21

标签 java string

你好,我是 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/

相关文章:

java - 在 alpine/Jprofile 10 中运行 jpenable 时出现 UnsatisfiedLinkError

java - 如何解决javax.el.MethodNotFoundException

java - Spring Batch - 是否可以在 FlatFileReader 中有一个动态列?

Python 2.7编辑一串字符

java - 理解Java中字节的掩码

java - 日期的 boolean 编码

JAVA - 忽略包含 "#"的部分字符串

Ruby 大写在 map 方法中不起作用

regex - 以编程方式在代码中查找连接字符串

c - argv 输出错误?