将删除多少空格?

在 Java 中,我有一个这样的 String:

"     content     ".

Will String.trim() remove all spaces on these sides or just one space on each?

246796 次浏览

它会移除两边的所有空格。

trim()将删除所有前导和尾随空白。但是要注意: 您的字符串没有更改。trim()将返回一个新的字符串实例。

Trim ()对双方都有效。

源代码(反编译) :

  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 低于空格字符的所有字符都被删除。

当有疑问时,编写一个单元测试:

@Test
public void trimRemoveAllBlanks(){
assertThat("    content   ".trim(), is("content"));
}

NB: of course the test (for JUnit + Hamcrest) doesn't fail

字符串类见 空气污染指数:

返回字符串的副本,忽略前导空格和尾随空格。

两边的空格都被删除了:

Note that trim() does not change the String instance, it will return a new object:

 String original = "  content  ";
String withoutWhitespace = original.trim();


// original still refers to "  content  "
// and withoutWhitespace refers to "content"

Javadoc for String has all the details. Removes white space (space, tabs, etc ) from both end and returns a new string.

如果您想检查什么将做一些方法,您可以使用 BeanShell。这是一个尽可能接近 Java 的脚本语言。一般来说,它是用一些放松来解释 Java 的。这种语言的另一种选择是 好极了语言。这两种脚本语言都提供了从解释语言中了解"读取-求值-输出"循环的便利。所以你可以运行控制台,然后输入:

"     content     ".trim();

在按下 Enter(或 Groovy 控制台中的 Ctrl+R)之后,您将看到结果是 "content"

不过,需要指出的一点是,String.trim 对“空格”有一个特殊的定义。它不会删除 Unicode 空格,但也会删除您可能不认为是空格的 ASCII 控制字符。

此方法可用于从字符串的开头和结尾处修剪空格; 实际上,它还可以修剪所有 ASCII 控制字符。

If possible, you may want to use Commons Lang's StringUtils.strip(), which also handles Unicode whitespace (and is null-safe, too).

One very important thing is that a string made entirely of "white spaces" will return a empty string.

如果一个 string sSomething = "xxxxx"(其中 x代表空格) ,则 sSomething.trim()将返回一个空字符串。

如果一个 string sSomething = "xxAxx",其中 x代表空格,sSomething.trim()将返回 A

如果 sSomething ="xxSomethingxxxxAndSomethingxElsexxx"sSomething.trim()将返回 SomethingxxxxAndSomethingxElse,请注意字与字之间的 x的数目没有改变。

如果您想要一个整洁的打包字符串结合 trim()与正则表达式,如本文所示: 如何使用 Java 删除字符串中重复的空格?

订单对结果来说是没有意义的,但是 trim()会更有效率。希望它能有所帮助。

String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");

从 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>'&#92;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>'&#92;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>'&#92;u0020'</code>, and let
* <i>m</i> be the index of the last character in the string whose code
* is greater than <code>'&#92;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>,&nbsp;<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 方法。

基于 Java 文档 给你.trim()取代了通常称为空格的“ u0020”。

但是请注意,“ u00A0”(Unicode 禁止中断空间 &nbsp;)也被视为一个空格,而且 .trim()不会删除这个。这在 HTML 中尤其常见。

为了移除它,我使用:

tmpTrimStr = tmpTrimStr.replaceAll("\\u00A0", "");

讨论了这个问题的一个实例 给你

Javatrim()删除空格的示例:

public class Test
{
public static void main(String[] args)
{
String str = "\n\t This is be trimmed.\n\n";


String newStr = str.trim();     //removes newlines, tabs and spaces.


System.out.println("old = " + str);
System.out.println("new = " + newStr);
}
}

输出

old =
This is a String.




new = This is a String.

若要只为 String 保留一个实例,可以使用以下方法。

str = "  Hello   ";

或者

str = str.trim();

那么 str字符串的值就是 str = "Hello"

If your String input is:

String a = "   abc   ";
System.out.println(a);

是的,输出将是“ abc”; But if your String input is:

String b = "    This  is  a  test  "
System.out.println(b);

输出为 This is a test So trim only removes spaces before your first character and after your last character in the string and ignores the inner spaces. 这是我的代码的一部分,略微优化了内置的 String修剪方法,删除了字符串中的第一个和最后一个字符之前和之后的内部空格。希望能有帮助。

public static String trim(char [] input){
char [] output = new char [input.length];
int j=0;
int jj=0;
if(input[0] == ' ' )    {
while(input[jj] == ' ')
jj++;
}
for(int i=jj; i<input.length; i++){
if(input[i] !=' ' || ( i==(input.length-1) && input[input.length-1] == ' ')){
output[j]=input[i];
j++;
}
else if (input[i+1]!=' '){
output[j]=' ';
j++;
}
}
char [] m = new char [j];
int a=0;
for(int i=0; i<m.length; i++){
m[i]=output[a];
a++;
}
return new String (m);
}