java的String类下substring方法源码解读
/** * Returns a 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. <p> * Examples: * <blockquote><pre> * "unhappy".substring(2) returns "happy" * "Harbison".substring(3) returns "bison" * "emptiness".substring(9) returns "" (an empty string) * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if * {@code beginIndex} is negative or larger than the * length of this {@code String} object. */ 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); } /** * Returns a string that is a substring of this string. The * substring begins at the specified {@code beginIndex} and * extends to the character at index {@code endIndex - 1}. * Thus the length of the substring is {@code endIndex-beginIndex}. * <p> * Examples: * <blockquote><pre> * "hamburger".substring(4, 8) returns "urge" * "smiles".substring(1, 5) returns "mile" * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * {@code beginIndex} is negative, or * {@code endIndex} is larger than the length of * this {@code String} object, or * {@code beginIndex} is larger than * {@code endIndex}. */ public String substring(int beginIndex, int endIndex) { // 判断边界条件,如果第一个参数(也就是起始下标小于0,那就下标访问越界抛异常) if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } // 判断边界条件,如果第二个参数(也就是起始截止下标大于字符串的长度,那就下标访问越界抛异常) if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } // 截取的长度是后面参数减去前面参数 int subLen = endIndex - beginIndex; // 如果长度小于0,也就是第二个参数大于第一个参数,那就抛异常 if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } // 返回从beginIndex开始,截取长度为subLen的字符串 return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); }