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

问题描述 投票:118回答:17

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

"     content     ".

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

java string trim
17个回答
168
投票

All of them

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

〜引用自Java 1.5.0文档

(但是您为什么不尝试一下并自己看看呢?)


3
投票

如果您的字符串输入是:

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

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

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

2
投票

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


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()会更有效率。希望对您有所帮助。


2
投票

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


0
投票

Trim()对双方都有效。


0
投票

Javadoc for String具有所有详细信息。从两端删除空格(空格,制表符等)并返回新字符串。


0
投票

如果要检查将执行某些方法的方法,则可以使用BeanShell。它是一种脚本语言,旨在与Java尽可能接近。一般来说,它是对Java的一些轻松的解释。这种类型的另一种选择是Groovy语言。这两种脚本语言都提供了方便的Read-Eval-Print循环(从解释语言中了解)。因此,您可以运行控制台,只需键入:


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

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


27
投票

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

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

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


26
投票

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

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

[如果可能,您可能要使用Commons Lang的StringUtils.strip(),它也处理Unicode空格(也是null安全的。)


15
投票

关于字符串类,请参见API

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

两边的空格都被删除:

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

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

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

13
投票

基于Java文档here.trim()替换了通常称为空白的'\ u0020'。

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

要删除它,我使用:

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

here中讨论了此问题的示例。


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.

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

注意,在开始并确定长度后,它将调用String类的子字符串方法。


3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.