If this String
object represents an empty character sequence, or the first and last characters of character sequence represented by this String
object both have codes greater than '\u0020'
(the space character), then a reference to this String
object is returned.
Otherwise, if there is no character with a code greater than '\u0020'
in the string, then a new String
object representing an empty string is created and returned.
Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020'
, and let m be the index of the last character in the string whose code is greater than '\u0020'
. A new String
object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1)
.
This method may be used to trim whitespace (as defined above) from the beginning and end of a string.
Returns:A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space. ‘u\0020’之前的字符都会被清除,所以要保留\t,\n的要慎用trim()。
明白了后,我们再看一下贴出的原代码,返回的是没有制表符的的字符串,public String trim() {
int start = offset, last = offset + count - 1;
int end = last;
while ((start <= end) && (value[start] <= ' ')) {
start++;
}
while ((end >= start) && (value[end] <= ' ')) {
end--;
}
if (start == offset && end == last) {
return this;
}
return new String(start, end - start + 1, value);
}。
如果我们在项目中,不需要去除2端的空白,只去除最右端的空白,则:
public String TrimRight(String sString){
String sResult = "";
if (sString.startsWith(" ")){
sResult = sString.substring(0,sString.indexOf(sString.trim().substring(0, 1))
+sString.trim().length());
}
else sResult = sString.trim();
return sResult;
}
好了,trim()方法介绍到这里了,也给自己多去了解一些底层的东西,这样才会对一个函数更加清楚和透彻,方便以后更好的应用。