【问题标题】:How many spaces will Java String.trim() remove?Java String.trim() 将删除多少个空格?
【发布时间】:2011-01-13 00:31:10
【问题描述】:

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

"     content     ".

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

【问题讨论】:

  • 致反对者:你的行为是居高临下的。这个问题详细而具体,写得清晰而简单,至少有其他地方的程序员感兴趣。人们可能不知道在哪里可以找到 javadoc 或源代码。我们的工作是帮助他们,而不是因为他们的无知而抨击他们。
  • @subtenante,你是对的。我什至为人们之前问过谷歌的问题辩护。但是,像这样简单的事情应该自己进行测试,而且 IMO 绝不应该保证在问答网站上发布问题。标题具有误导性,Q 对于所有阅读它的人来说都是浪费时间。
  • @Chris : oneat 让我有机会查看源代码。我学到了很多关于 trim() 的知识。否则我不会。每个人都要为自己的时间花费负责。 oneat 不应该因为我们无法从他看似幼稚的问题中获利而受到责备。
  • @skaffman:(c) 应该是“试试看”,然后才 (d) 询问 SO。
  • 这个问题似乎离题了,因为它是关于任何人都应该能够在一分钟内找到并测试的手册。

标签: java string trim


【解决方案1】:

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

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

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

【讨论】:

  • 请一个刚学会如何做 System.out.println 的新程序员做一个单元测试,看看结果如何...
【解决方案2】:

如果您的字符串输入是:

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

【讨论】:

  • 这个答案中的前几条语句是完全错误的,输出将 not 是“abc”。也许你忘了.trim()System.out.println(a);
【解决方案3】:

All of them.

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

~ 引用自 Java 1.5.0 文档

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

【讨论】:

  • 我不得不投反对票,因为这个答案没有涵盖文档中“空白”的含义。 Chararacter.isWhitespace 为真似乎是合乎逻辑的,但这不是“空白”的含义..
  • @user2864740:此答案并非旨在对trimisWhiteSpace 等进行全面分析,也不是讨论Java 文档中的歧义;这是对上面提出的具体问题的直接回答——即trim 方法是删除单个空格还是多个空格?
  • 我知道不是。我投了反对票,因为它没有指出这一点,即使是顺便说一句。在任何情况下,我都无法撤消我的投票,除非它已更新(但最少)。
【解决方案4】:

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

str = "  Hello   ";

str = str.trim();

那么str String 的值就是str = "Hello"

【讨论】:

    【解决方案5】:

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

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

    要删除它,我使用:

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

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

    【讨论】:

    • 基于 Javadoc,它删除了 前导和尾随空格,其中包括空格、制表符、换行符、换页符、...以及 排除 i> 不是前导或尾随的字符。
    • 谢谢,帮我分配
    【解决方案6】:

    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】:

      来自 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方法。

      【讨论】:

      • 其中“空白”是“值小于或等于 \x20 的字符”.. 非常棒。
      【解决方案8】:
      String formattedStr=unformattedStr;
      formattedStr=formattedStr.trim().replaceAll("\\s+", " ");
      

      【讨论】:

      • 这与问题无关。
      • @Mark 但意外的是,当我打开这个问题时,我正在寻找它......
      • 这也是没有意义的。 trim() 已经做了repkaceAll() 会做的事情,如果还有什么事情要做的话。
      • @EJP replaceAll 也会用单个空格替换字符串中的空格,而 trim 只会处理前导和尾随空格
      【解决方案9】:

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

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

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

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

      如果您想要一个整洁的打包字符串,请将@​​987654333@ 与正则表达式结合起来,如本文所示:How to remove duplicate white spaces in string using Java?

      顺序对结果没有意义,但trim() first 会更有效率。希望对您有所帮助。

      【讨论】:

        【解决方案10】:

        来自源代码(反编译):

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

        【讨论】:

          【解决方案11】:

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

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

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

          【讨论】:

          • 似乎是对设计师部分的严重疏忽......并且文档的过度技术性工作并没有太大帮助。
          • 太棒了!您提出了 StackOverflow 上有史以来最简单的问题,并找到了一些明智的说法。你是比赛的功劳。
          • @MarkMcKenna:我一直发现这些所谓的超级简单的编程问题(修剪字符串、查找文件扩展名等)总是隐藏着复杂性。这对我们的工艺和工具有点失望。
          【解决方案12】:

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

          "     content     ".trim();
          

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

          【讨论】:

          • 所以要理解 Java 中的方法,他应该去学习一门全新的语言。真的吗?
          【解决方案13】:

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

          【讨论】:

            【解决方案14】:

            String 类见API

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

            去掉两边的空格:

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

             String original = "  content  ";
             String withoutWhitespace = original.trim();
            
             // original still refers to "  content  "
             // and withoutWhitespace refers to "content"
            

            【讨论】:

            • 实际上没有什么可以改变 String 实例(除了一些可能导致 VM 崩溃的脏东西)
            【解决方案15】:

            Trim() 对双方都有效。

            【讨论】:

              【解决方案16】:

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

              【讨论】:

              • 它将删除所有前导和尾随 空格。
              【解决方案17】:

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

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2011-01-20
                • 1970-01-01
                • 2021-12-23
                • 2014-02-18
                • 1970-01-01
                • 2012-01-30
                相关资源
                最近更新 更多