117

在Java中,我有一个这样的字符串:

"     content     ".

String.trim()删除这些边上的所有空格还是只删除每个空格?

4

17 回答 17

168

他们所有人

返回:删除了前导和尾随空格的此字符串的副本,或者如果它没有前导或尾随空格,则返回此字符串。

~ 引用自 Java 1.5.0 文档

(但你为什么不自己试试看呢?)

于 2010-02-04T10:27:39.790 回答
33

从源代码(反编译):

  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 低于空格字符的字符,在开头和结尾都被删除。

于 2010-02-04T10:28:37.993 回答
27

如有疑问,请编写单元测试:

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

注意:当然测试(对于 JUnit + Hamcrest)不会失败

于 2010-02-04T10:29:47.917 回答
26

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

此方法可用于从字符串的开头和结尾修剪空白;事实上,它也会修剪所有 ASCII 控制字符。

如果可能,您可能希望使用 Commons Lang 的 StringUtils.strip(),它还可以处理 Unicode 空白(并且也是 null 安全的)。

于 2010-02-04T10:49:08.573 回答
15

请参阅String 类的API :

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

两边的空格被删除:

注意trim()不改变String实例,它会返回一个新对象:

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

 // original still refers to "  content  "
 // and withoutWhitespace refers to "content"
于 2010-02-04T10:31:55.693 回答
13

根据此处的 Java 文档,.trim()替换通常称为空白的 '\u0020'。

但请注意,'\u00A0'(Unicode NO-BREAK SPACE &nbsp;)也被视为空格,.trim()不会删除它。这在 HTML 中尤其常见。

要删除它,我使用:

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

这里讨论了这个问题的一个例子。

于 2012-12-29T20:39:41.733 回答
8

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.
于 2013-04-02T08:52:18.940 回答
4

来自java docs(字符串类源),

/**
 * 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 方法。

于 2012-12-18T10:50:20.477 回答
3

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

于 2010-02-04T10:27:39.277 回答
3

如果您的字符串输入是:

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

是的,输出将是“abc”;但是,如果您的字符串输入是:

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

输出将是This is a test 所以修剪只删除字符串中第一个字符之前和最后一个字符之后的空格,并忽略内部空格。这是我的一段代码,它略微优化了内置的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);
  }
于 2015-02-01T12:25:47.830 回答
2

它将删除两侧的所有空格。

于 2010-02-04T10:27:16.017 回答
2

一件非常重要的事情是完全由“空格”组成的字符串将返回一个空字符串。

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

如果 a代表空格,string sSomething = "xxAxx"将返回。xsSomething.trim()A

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

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

顺序对结果没有意义,但trim()首先会更有效率。希望能帮助到你。

于 2011-09-02T22:48:32.223 回答
2

要为字符串只保留一个实例,您可以使用以下内容。

str = "  Hello   ";

或者

str = str.trim();

然后str字符串的值将是str = "Hello"

于 2013-05-02T22:07:02.097 回答
0

Trim() 适用于双方。

于 2010-02-04T10:27:49.230 回答
0

String 的Javadoc包含所有详细信息。从两端删除空格(空格、制表符等)并返回一个新字符串。

于 2010-02-04T10:32:16.600 回答
0

如果你想检查什么会做一些方法,你可以使用BeanShell。它是一种脚本语言,旨在尽可能接近 Java。一般来说,它被解释为带有一些放松的Java。这种类型的另一种选择是Groovy语言。这两种脚本语言都提供了从解释语言中知道的方便的 Read-Eval-Print 循环。所以你可以运行控制台并输入:

"     content     ".trim();

按下(或在 Groovy 控制台中)后,您会看到"content"结果。EnterCtrl+R

于 2010-02-04T10:44:36.710 回答
0
String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");
于 2012-12-18T10:26:50.023 回答