在Java中,我有一个这样的字符串:
" content ".
String.trim()
会删除这些边上的所有空格还是每边只有一个空格?
发布于 2010-02-04 18:28:38
从源代码(反编译):
public String trim()
{
int i = this.count;
int j = 0;
int k = this.offset;
char[] arrayOfChar = this.value;
while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
++j;
while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
--i;
return (((j > 0) || (i < this.count)) ? substring(j, i) : this);
}
您可以看到的两个while
表示在开头和结尾的unicode低于空格字符的所有字符都将被删除。
发布于 2012-12-30 04:39:42
基于Java docs here,.trim()
替换了'\u0020‘,后者通常称为空格。
但请注意,'\u00A0‘(Unicode NO-BREAK SPACE
)也被视为一个空格,.trim()
不会删除它。这在HTML中尤其常见。
要删除它,我使用:
tmpTrimStr = tmpTrimStr.replaceAll("\\u00A0", "");
here讨论了这个问题的一个例子。
发布于 2012-12-18 18:50:20
从java文档(字符串类源代码),
/**
* Returns a copy of the string, with leading and trailing whitespace
* omitted.
* <p>
* If this <code>String</code> object represents an empty character
* sequence, or the first and last characters of character sequence
* represented by this <code>String</code> object both have codes
* greater than <code>'\u0020'</code> (the space character), then a
* reference to this <code>String</code> object is returned.
* <p>
* Otherwise, if there is no character with a code greater than
* <code>'\u0020'</code> in the string, then a new
* <code>String</code> object representing an empty string is created
* and returned.
* <p>
* Otherwise, let <i>k</i> be the index of the first character in the
* string whose code is greater than <code>'\u0020'</code>, and let
* <i>m</i> be the index of the last character in the string whose code
* is greater than <code>'\u0020'</code>. A new <code>String</code>
* object is created, representing the substring of this string that
* begins with the character at index <i>k</i> and ends with the
* character at index <i>m</i>-that is, the result of
* <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
* <p>
* This method may be used to trim whitespace (as defined above) from
* the beginning and end of a string.
*
* @return A copy of this string with leading and trailing white
* space removed, or this string if it has no leading or
* trailing white space.
*/
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
注意,在获得start和length之后,它调用String类的substring方法。
https://stackoverflow.com/questions/2198875
复制相似问题