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);
    }
  • 相关阅读:
    leetcode 296 题解(暴力破解)
    2.7最大公约数(递归解法)
    2.6斐波那契数列(多分支递归)
    2.5翻转字符串(递归4 )
    2.4对arr数组元素求和
    2.3 用递归形式打印i到j
    2.2用递归方式解决阶问题
    2.1什么是递归?
    1.用数组的方式实现列表
    如何在电脑上安装Jupyter Notebook
  • 原文地址:https://www.cnblogs.com/ljdblog/p/5952183.html
Copyright © 2011-2022 走看看