码迷,mamicode.com
首页 > 其他好文 > 详细

String类的substring方法

时间:2016-10-12 13:48:26      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

下列程序的输出是什么?

class A { public static void main(String[] a) {
    String v = “base”;      v.concat(“ball”);
    v.substring(1,5);       System.out.println(v);  }
}

分析:由于String是不可变的,当执行v.concat("ball")时,v本身还是指向“base”,当再执行v.substring(1,5)时,会报出界异常

技术分享

 

如下为concat的源码:可以看到,最后返回的是新的字符串

public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }

如下是substring源码:

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 substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
}

 

String类的substring方法

标签:

原文地址:http://www.cnblogs.com/ljdblog/p/5952183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!