System.out.println("----"+"".substring(1).length());//question

System.out.println("----"+"1".substring(1).length());第一个出现错误是肯定的,我想了解为什么第二个不报错呢输出来的时候什么都没有,为什么,原因

解决方案 »

  1.   

    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 对象的长度。
    要大于长度才抛错误
      

  2.   

    System.out.println("----"+"".substring(1).length());//question
    //因为 String index out of range: -1 ,""  -- 空串  长度为0,而你的substring截取的index从1开始 System.out.println("----"+"1".substring(1).length());
      

  3.   


    //你从第一个字符而不是第0个字符开始截取,也就是什么都没截取到,返回空串 相当于
    System.out.println("----"+"".legth());
    //当然不会报错
      

  4.   

    跟数组下标越界是一个道理,string实质还是一个数组。""字符串等同于一个长度为0的数组,没有任何元素,substring(1)取0-1的元素就会越界
    “1”有一个元素,刚好满足
      

  5.   

    看一源码吧:
        
    public String substring(int beginIndex) {
    return substring(beginIndex, count);
        }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);
        }
      

  6.   

    第一句报错。
    第二句执行时 打印 ----0。 // "1".substring(1).length() 为 0 
      

  7.   

    System.out.println("----"+"".substring(1).length());//question
    这个是"----"字符串和 "".substring(1).length()) ,而“”是空的没有索引为1的子串所以报错啊。
    你要将"----"+"".substring(1).length() 分成 "----" 和 "".substring(1).length())两个字符串来看待System.out.println("----"+"1".substring(1).length());
      

  8.   

    看下jdk源码就清晰了, 第2个截取到是个空串。
    只有beginindex> length在报错;beginindex= length,得到空串
      

  9.   

    subString(1),表示从1到最后,就是一个空串啊,
      

  10.   

    没有打印----0
    就是----
    就像是null一样