java中的String.substring()
为什么这会留下空白?第八个位置不应该越界吗 另外,为什么s1.charAt8提示出绑定错误?他们是否使用不同的方法来处理问题?string.substringint id返回字符串的子字符串,该字符串从索引id开始。id是索引,但不是位置 记住,索引从0开始计数! 请检查一下房间 子字符串方法的一部分如下所示:java中的String.substring(),java,Java,为什么这会留下空白?第八个位置不应该越界吗 另外,为什么s1.charAt8提示出绑定错误?他们是否使用不同的方法来处理问题?string.substringint id返回字符串的子字符串,该字符串从索引id开始。id是索引,但不是位置 记住,索引从0开始计数! 请检查一下房间 子字符串方法的一部分如下所示: import java.util.*; public class Test2{ public static void main(String[] args){ String
import java.util.*;
public class Test2{
public static void main(String[] args){
String s1 = "Delivery";
String s2 = s1.substring(8);
System.out.println(s2);
}
}
仅当beginIndex大于字符串长度时,substring方法才会引发StringIndexOutOfBoundsException,如下所示,代码取自string类substring方法:
同样,Javadoc中也解释了这一点,您可以查看:
返回作为此字符串的子字符串的新字符串。子串
从指定索引处的字符开始,并扩展到
这个字符串的结尾。示例:
substring2返回快乐
substring3返回bison
empty.substring9返回一个空字符串
如果beginIndex为负值或大于字符串长度,则会引发IndexOutOfBoundsException。在您的例子中,beginIndex是8,字符串的长度也是8。这就是你没有IndexOutOfBoundsException的原因
希望这有帮助 建议您在IDE中运行代码并进行调试 进入方法子字符串,您的查询将得到回答 检查Substring方法的源代码
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
请参见此处有关字符串的Java文档: 你的s1长度是7 charAt方法如下所示:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1875)
at com.iqp.standalone.Sample.main(Sample.java:14)
当然,它会给你错误 不,可以在字符串的末尾开始子字符串,它只提供空字符串,字符串的长度为0。请检查。文档中说“Throws:IndexOutOfBoundsException-如果beginIndex为负值或大于此字符串对象的长度。”您可以将其理解为严格意义上的更大。在您的示例中,beginIndex允许等于length。两者都是8。不,它不返回字符,在本例中,这是不可能的。在示例中,它返回一个空字符串。
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1875)
at com.iqp.standalone.Sample.main(Sample.java:14)
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}