[英]java substring not working as expected
我正在尝试在Java中使用子字符串函数,但是它一直抛出错误,我想知道为什么? 从逻辑上讲,该代码似乎很好,但是为什么会引发此错误
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
我在文档子字符串中阅读的内容带有2个参数
substring(whereIwantToStart,howManyCharactersToshow)
下面是我的代码
String test = "160994";
System.out.println(test.substring(2,1)); //output should be 09 why error?
有人可以解释我哪里错了吗? 请我解释一下。 谢谢 :)
参见文档 :
公共字符串子字符串(int beginIndex,int endIndex)
返回一个新字符串,该字符串是该字符串的子字符串。 子字符串从指定的beginIndex开始,并扩展到索引endIndex-1处的字符。因此,子字符串的长度为endIndex-beginIndex。
您需要"160994".substring(2, 4)
来获取09
。
对于您所需的输出,请使用-
System.out.println(test.substring(2,4));
这是Java中子字符串的格式
public String substring(int beginIndex, int endIndex)
您指定从索引2开始到索引1结束,这就是为什么它将异常索引抛出范围之外的原因。
要获得09的输出,您需要
System.out.println(test.substring(2,4));
附录-Java文档https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
结束索引应大于开始索引。 要获得输出为'09',您应该提供结束索引为4 test.substring(2,4);
返回一个新字符串,该字符串是该字符串的子字符串。 该
子字符串从指定的beginIndex
开始,并扩展到索引endIndex - 1
处的字符。因此,子字符串的长度为
endIndex-beginIndex
。
在以下情况下,将抛出StringIndexOutOfBoundsException
public String substring(int startIndex, int endIndex)
:此方法返回新的String对象,其中包含给定字符串从指定的startIndex到endIndex的子字符串。
让我们通过下面给出的代码了解startIndex和endIndex。
String s="hello";
System.out.println(s.substring(0,2));
输出: he
注意 :
endIndex> startIndex
在您的情况下:在1到2之间更改
String test = "160994";
System.out.println(test.substring(2, 4)); //output should be 09
输出: 09
字符串测试=“ 160994”;
的System.out.println(test.substring(2,1));
子字符串的意思是(beginIndex,endIndex)和endIndex应该大于beginIndex。并且您的value(09)应该保持在beninIndex(这是起始索引)和endIndex(这是最后一个索引)之间。
并且您采用了endIndex 1,因此由于您的beginIndex大于endIndex而出现错误。
如果你想得到Ans。 09,则您必须放置endIndex 4。
行将是:-System.out.println(test.substring(2,4));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.