今天有时光,看了下String类中的substring()办法,现扼要剖析以下:
/**
* Returns a new string that is a substring of this string. The substring begins
* with the character at the specified index and extends to the end of this string.
* 上面的这段话的意思是,它会返回一个新的字符串,这个新的字符串是本来字符串的一部份,
* 从某个下标的字母开端,一直到这个字符串的停止。
* 例如:"unhappy".substring(2),从下标2开端,到停止->happy
*
**/
public String substring(int beginIndex) {
return substring(beginIndex, count);
}
注:The count is the number of characters in the String.
可以看出如果只是指定了开真个下标,那即是默许将该下标以后的所有字符都作为新的字符串的一部份。
接着看String.substring(int beginIndex, int endIndex)办法:
/**
* Returns a new string that is a substring of this string. The
* substring begins at the specified <code>beginIndex</code> and
* extends to the character at index <code>endIndex - 1</code>.
* Thus the length of the substring is <code>endIndex-beginIndex</code>.
* 从这段解释中也可看出是左闭右开的(即[a,b),包含下标为a的但不包含下标为b的元素)。
* 例如:"hamburger".substring(4, 8) returns "urge"
**/
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
在String类的一开端定义了一些变量:
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** Cache the hash code for the string */
private int hash; // Default to 0
// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value; // 保留的字符串
this.offset = offset; // 开真个地位
this.count = count; // 字符数量
}
今天有时光,看了下String类中的substring()办法,现扼要剖析以下:
/**