String.trim()源码解析

trim()这个方法一般用来消除字符串两边的空格,但是内部是如何实现的呢?

附上源码:

public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */

        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }

从源码可以看出,这个方法实际上是将字符串除了两端ASCII码小于空格的字符之外的部分截取出来返回,如果没有空格则将原字符串返回。

而这里也要再说一下substring()这个方法,同样附上源码:

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);
    }

从substring()的源码可以看出,当输入的起始索引与同字符串的起始索引一致时,返回原字符串,而如果不一致且不抛异常的情况下,则将起始索引部分从字符串中截取下来,注意这里是新new了一个String对象!!然后将它返回。

所以说,这也是一个坑,举个例子:

        String str = "ab";
        String str1 = (" a"+"b ").trim();
        String str2 = ("a"+"b").trim();
        System.out.println(str==str1);
        System.out.println(str==str2);

上面str1因为两边有空格,所以调用trim()方法时,内部的substring()方法将会将截取的部分new成一个String对象,所以str==str1为false,因为一个指向常量池中的值,一个指向堆中的对象,地址不同;而str2因为两边并没有空格,所以trim()

方法直接返回原对象,所以str==str2为true,因为两个都是指向常量池中的值,且常量池中的值是唯一的,所以str和str2都指向常量池中ab的值,地址相同。

猜你喜欢

转载自www.cnblogs.com/wujianwu/p/11239574.html