String.trim () parse the source code

trim () This method is generally used to eliminate the spaces on both sides of the string, but the interior is how to achieve it?

Attach Source:

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

As can be seen from the source, this method is actually a string of characters except both ends is less than the ASCII space portion interception return if there is no space will return to the original string.

And also here to tell you the substring () This method is also accompanied by source:

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

As can be seen substring () of source code, when the input index coincides with the start character string with the starting index, return the original string, and in the case not throw exception if not, then starting from the index portion string interception, note that this is a new new string object! ! Then it will return.

So, this is a pit, for example:

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

Because both sides of a space above str1, the call to a new trim portion String object () method, the inside of the substring () method will be taken, so str == str1 is false, a pointer value as the constant pool, a pointer to objects in the heap, a different address; and str2 because both sides and there is no space, so trim ()

Method returns the original object, str == str2 is true, because two points are the values ​​of the constant pool, the pool and the value of the constant is unique, str and str2 point ab value of the constant pool, the address the same.

Guess you like

Origin www.cnblogs.com/wujianwu/p/11239574.html