public String delDel(String str) {
if (str.length() < 4)
return str;
if (str.substring(1,4).equals("del"))
return str.substring(0, 1) + str.substring(4, str.length());
else
return str;
}如果我运行delDel(" adel "),它返回a,但是adel的长度是4,这意味着最后一个字符串索引是3,为什么str.substring(4,str.length() )没有越界?
发布于 2019-07-04 12:50:04
以下代码是String类的substring方法在java中的实现:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}可以看出,beginIndex仅被检查为不小于零,并且endIndex仅被检查为大于它的字符串的"value.length“。然后,如果此条件通过,则请求的子字符串将由以下代码创建:
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}在本例中,由于计数将变为零(4-4),因此'this.value = "".value;‘
发布于 2019-07-04 13:32:07
还有一个更复杂的substring()版本,它同时接受开始和结束索引号: substring(int start,int end)返回从开始索引号开始直到结束索引的字符串。
String str = "Hello";
String a = str.substring(2, 4); // a is "ll" (not "llo")
String b = str.substring(0, 3); // b is "Hel"
String c = str.substring(4, 5); // c is "o" -- the last char

上面的c示例使用子字符串(4,5)来获取最后一个字符。5比最后一个字符的索引多1。
https://stackoverflow.com/questions/56880575
复制相似问题