Java String.trim()删除了多少个空格?

时间:2010-02-04 10:25:52

标签: java string trim

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

"     content     ".

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

17 个答案:

答案 0 :(得分:169)

All of them

  

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

     
    

〜引自Java 1.5.0 docs

  

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

答案 1 :(得分: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低于空格字符的所有字符都将被删除。

答案 2 :(得分:27)

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

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

NB :当然测试(对于JUnit + Hamcrest)没有失败

答案 3 :(得分:26)

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

  

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

如果可能的话,你可能想使用Commons Lang的StringUtils.strip(),它也处理Unicode空白(并且也是空的安全)。

答案 4 :(得分:15)

请参阅API了解String类:

  

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

双方的空白被删除:

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

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

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

答案 5 :(得分:13)

基于Java文档here.trim()取代了'\ u0020',通常称为空格。

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

要删除它,我使用:

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

讨论了这个问题的一个例子here

答案 6 :(得分:8)

删除空格的Java trim()示例:

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.

答案 7 :(得分:4)

来自java docs(String class source),

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

答案 8 :(得分:3)

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

答案 9 :(得分:3)

如果你的字符串输入是:

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

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

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

输出为This is a test 因此trim仅删除第一个字符之前和字符串中最后一个字符之后的空格并忽略内部空格。 这是我的一段代码,它稍微优化了内置String trim方法,删除了内部空格,并删除了字符串中第一个和最后一个字符前后的空格。希望它有所帮助。

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);
  }

答案 10 :(得分:2)

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

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

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

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

如果您想要一个整齐的打包字符串,请将trim()与正则表达式结合起来,如以下帖子所示:How to remove duplicate white spaces in string using Java?

顺序对结果毫无意义,但trim()首先会更有效率。希望它有所帮助。

答案 11 :(得分:2)

要仅保留String的一个实例,可以使用以下内容。

str = "  Hello   ";

str = str.trim();

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

答案 12 :(得分:2)

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

答案 13 :(得分:0)

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

答案 14 :(得分:0)

如果您想查看某些方法会做什么,可以使用BeanShell。它是一种脚本语言,旨在尽可能接近Java。一般来说,它解释Java有一些放松。另一种选择是Groovy语言。这两种脚本语言都可以通过解释语言提供方便的Read-Eval-Print循环。所以你可以运行控制台,只需输入:

"     content     ".trim();

按下"content"(或Groovy控制台中的Enter)后,您会看到Ctrl+R

答案 15 :(得分:0)

String的

Javadoc包含所有细节。从两端移除空格(空格,制表符等)并返回一个新字符串。

答案 16 :(得分:0)

Trim()适用于双方。

相关问题