黑马程序员技术交流社区

标题: subString角标越界问题 [打印本页]

作者: android-liu    时间: 2015-3-11 20:00
标题: subString角标越界问题
  1. String str="ddd";
  2. String ss=str.substring(3);
  3. System.out.println(ss);
复制代码

大家帮我看看字符串角标为什么没有出越界异常
作者: 路文龙    时间: 2015-3-11 21:29
String类源码实现
  1. /**
  2.      * Returns a string that is a substring of this string. The
  3.      * substring begins with the character at the specified index and
  4.      * extends to the end of this string. <p>
  5.      * Examples:
  6.      * <blockquote><pre>
  7.      * "unhappy".substring(2) returns "happy"
  8.      * "Harbison".substring(3) returns "bison"
  9.      * "emptiness".substring(9) returns "" (an empty string)
  10.      * </pre></blockquote>
  11.      *
  12.      * @param      beginIndex   the beginning index, inclusive.
  13.      * @return     the specified substring.
  14.      * @exception  IndexOutOfBoundsException  if
  15.      *             {@code beginIndex} is negative or larger than the
  16.      *             length of this {@code String} object.
  17.      */
  18.     public String substring(int beginIndex) {
  19.         if (beginIndex < 0) {
  20.             throw new StringIndexOutOfBoundsException(beginIndex);
  21.         }
  22.         int subLen = value.length - beginIndex;
  23.         if (subLen < 0) {
  24.             throw new StringIndexOutOfBoundsException(subLen);
  25.         }
  26.         return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
  27.     }
复制代码

作者: Rorine    时间: 2015-3-11 22:11
不知道你有没有听说过这样一句话:字符串的截取是包括头不包括尾的
作者: wf111sxwf    时间: 2015-3-11 23:10
ddd是 0 1 2没有3  更没有3以后的  。。。。subString (int index)是从index开始到length 你3已然越界了 少年
作者: ccl|r    时间: 2015-3-11 23:28
在基础班还没上到这




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2