zoukankan      html  css  js  c++  java
  • String类的substring方法

    下列程序的输出是什么?

    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);
    }
  • 相关阅读:
    牛券
    探险
    雷达安装
    智力大冲浪
    奶牛玩杂技
    BJWC2008 秦腾与教学评估
    JSOI2010 部落划分
    作诗
    ASP.NET MVC4系列验证机制、伙伴类共享源数据信息(数据注解和验证)
    正则表达式
  • 原文地址:https://www.cnblogs.com/ljdblog/p/5952183.html
Copyright © 2011-2022 走看看