String.trim()源碼解析

trim()這個方法通常用來消除字符串兩邊的空格,可是內部是如何實現的呢?this

附上源碼:spa

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碼小於空格的字符以外的部分截取出來返回,若是沒有空格則將原字符串返回。code

而這裏也要再說一下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對象!!而後將它返回。blog

因此說,這也是一個坑,舉個例子:索引

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的值,地址相同。get

相關文章
相關標籤/搜索