项目场景:
在对字符串进行操作的时候报了这个错,String index out of range: -4
原因分析:
这个错误的意思是字符串的索引越界了
一般都是在对字符串进行操作的时候引起的,例如
String str = "123"; //字符串的长度是3
str.substring(0,str.length()-4); //回报错String index out of range: -4
报这个错误是由于对字符串进行操作的过程中抛出了StringIndexOutOfBoundsException异常
总结:
下面的几种方法均有可能抛出上述异常
String.substring()
String.charAt()
String.codePointAt()
String.codePointBefore()
String.subSequence()
String.getChars()
String.getBytes()
本文解析了字符串索引越界错误,重点讲解了如何在substring(), charAt(), 等方法中避免StringIndexOutOfBoundsException,列举了可能引发异常的操作并提供解决方案。
1877

被折叠的 条评论
为什么被折叠?



