使用substring会产生一个StringIndexOutOfBoundsException:String index超出范围:-1 exception

时间:2015-07-16 12:00:12

标签: java

搜索时,标签处的字符串为 abc: xyz

但是这给出了

`StringIndexOutOfBoundsException`: String index out of range: -1 exception. 

在这一行:

tag = strLine.substring(0, strLine.indexOf(':'));

可能出现的错误是什么?

提前致谢!

4 个答案:

答案 0 :(得分:1)

strLine.substring(0, strLine.indexOf(':')); 

上面的代码将尝试从0(包括)子串到一些正int值。 但是strLine.indexOf(':')正在返回-1,而:中没有strLine。所以最后该方法变为subString(0, -1),它会给你错误: -

StringIndexOutOfBoundsException: String index out of range: -1 exception.

做这样的事情以防止: -

int i = strLine.indexOf(':')
if(i != -1)
tag = strLine.substring(0, i);
else {//handle error here}

OR

try{
tag = strLine.substring(0, strLine.indexOf(':'));
}
catch(StringIndexOutOfBoundsException ex){
// catch here
}

PS: - StringIndexOutOfBoundsException是一个运行时异常,不应该被捕获但是处理/修复。

答案 1 :(得分:0)

indexOf找不到子字符串时,结果为-1,这不是子字符串的允许参数。

答案 2 :(得分:0)

这表示您的字符串不包含symbol(:)。如果你的strLine =“xyz:abc”那么它将输出

String output="xyz:abc".substring(0, "xyz:abc".indexOf(':'));
System.out.println(output);

答案 3 :(得分:-1)

无论你提供什么字符串,它都可以正常工作。 请参阅以下计划供您参考:

public class Consistent {
    public static void main(String[] args) throws IOException {
        String s= "abc: xyz";
        String s1 = "abc";
        System.out.println(s.substring(0, s.indexOf(':')));
        System.out.println(s1.substring(0, s1.indexOf(':')));// This line will give error whatever you are getting, as it is not found
//to avoid first check if the String contains this identifier
if(s1.contains(":"))
System.out.println(s1.substring(0, s1.indexOf(':')));//It will work fine now
}
}