本文共 1293 字,大约阅读时间需要 4 分钟。
trim()方法实际上trim掉了字符串两端Unicode编码小于等于32(\u0020)的所有字符
/** * @return A string whose value is this string, with any leading and trailing white * space removed, or this string if it has no leading or * trailing white space. */ 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; }
trim()方法实际上的行为并不是”去掉两端的空白字符“,而是”截取中间的非空白字符“
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()无法像我们写String str = “abc”这样直接在常量池中创建对象,所以它返回的是一个new出来的对象,这个对象位于Heap内存中
转载地址:http://wwgxi.baihongyu.com/