String s1 = "t";
System.out.println(s1.substring(1));
它什么都没打印,但我想知道为什么它不会崩溃,它肯定是超出范围的例外或者我错过了什么?
答案 0 :(得分:6)
每http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#substring(int)
抛出:IndexOutOfBoundsException - 如果beginIndex为负数或 大于此String对象的长度。
这里,你的字符串长度为1,你的索引是1,它不是负数=>没有异常抛出。
有点不直观?是。但是substring()在索引选择方面有点不直观: - )
答案 1 :(得分:2)
来自Javadoc:
抛出: IndexOutOfBoundsException - 如果
beginIndex
为负数或大于此String对象的长度。
请注意更大这个词。在您的示例中,它不是(等于到字符串的长度)。
答案 2 :(得分:1)
在子串方法中有2个函数
1)substring(int 1,int 2)
在这里int 1 =开始位置从0开始
int 2 =结束位置从1开始计算
例如: -
String test = "STACKOVERFLOW";
String result = test.substring(0,5); // result is equal to stack
2)substring(int 1)
听到类似于上述(1)起点是int 1,(计数从0开始),结束点=字符串的最后位置
在你的问题中
String s1 = "t";
System.out.println(s1.substring(1)); // "t" 's end point index is the end of the string
// "t" 's start point index is 1 which is also equal to the end of the string in this case
当你s1.substring(1)等于""