4
回答
Java的String.substring为什么能够处理str.length()?
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

比如String a = "123456";为什么a.subString(a.length());也是有效的?a字符串没有a.length()这一位啊?

举报
kanlianhui
发帖于3年前 4回/812阅
共有4个答案 最后回答: 3年前

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);
}

public String(char value[], int offset, int count) {
	if (offset < 0) {
		throw new StringIndexOutOfBoundsException(offset);
	}
	if (count < 0) {
		throw new StringIndexOutOfBoundsException(count);
	}
	// 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);
}



看api对Arrays.copyOfRange的说明:

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case false is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.



--- 共有 1 条评论 ---
kanlianhui根据(T[]) new Object[newLength] 代码看应该是返回了char[0]。可惜最后的native方法不好确认 3年前 回复

a.subString(a.length())和a.charAt(a.length())逻辑不一样

chaAt返回的是value[index + offset],如果是取length的话会报错的,而substring返回的是

new String(offset + beginIndex, endIndex - beginIndex, value),也就是

new String(a.length(), 0, a.toCharArray())


new String(a.getBytes(), a.length(), 0)

即""

看API啊;

substring

public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。

示例:

"unhappy".substring(2) returns "happy"
 "Harbison".substring(3) returns "bison"
 "emptiness".substring(9) returns "" (an empty string)


参数:beginIndex- 起始索引(包括)。 返回:指定的子字符串。 抛出: IndexOutOfBoundsException- 如果beginIndex为负或大于此String对象的长度。

至于等于应该和字符串的存储有关了,最后都是有个结束标识的

引用来自“Cobbage”的评论

看API啊;

substring

public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。

示例:

"unhappy".substring(2) returns "happy"
 "Harbison".substring(3) returns "bison"
 "emptiness".substring(9) returns "" (an empty string)


参数:beginIndex- 起始索引(包括)。 返回:指定的子字符串。 抛出: IndexOutOfBoundsException- 如果beginIndex为负或大于此String对象的长度。

至于等于应该和字符串的存储有关了,最后都是有个结束标识的

上面说的和存储有关是错的

其实返回的是一个 new char; 也就是""




                       

--- 共有 2 条评论 ---
Cobbage回复 @kanlianhui : 对啊 [0][1][2][3][4] 3年前 回复
kanlianhui是new char[0] 吧 3年前 回复
顶部