117

In Java, I have a String like this:

"     content     ".

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

5
  • 197
    To the downvoters : your behaviour is condescendant. This question is detailed and specific, written clearly and simply, of interest to at least one other programmer somewhere. People may not know where to look to find the javadoc or the source code. Our job is to help them, not bashing them for being ignorant. Commented Feb 4, 2010 at 13:57
  • 14
    @subtenante, you're correct. I've even defended people for asking google'ish questions before. However, something as simple as this should be tested on one's own, and IMO, should NEVER warrant posting a question on a Q&A site. The title is misleading and the Q is a waste of time for all who read it. Commented Feb 4, 2010 at 16:34
  • 9
    @Chris : oneat gave me the occasion to look at the source code. I learned a lot about trim(). I wouldn't have otherwise. Everybody is responsible for his own spending of his time. oneat is not to be blamed for us being unable to get profit from his seemingly naive question. Commented Feb 4, 2010 at 16:43
  • 1
    @skaffman: (c) should be "try it and see", and only then (d) ask on SO. Commented Aug 25, 2013 at 22:48
  • 2
    This question appears to be off-topic because it is about something that anyone should be able to find in the manual AND test in under a minute. Commented Mar 23, 2014 at 1:17

17 Answers 17

168

All of them.

Returns: A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

~ Quoted from Java 1.5.0 docs

(But why didn't you just try it and see for yourself?)

Sign up to request clarification or add additional context in comments.

3 Comments

I had to down-vote as this answer does not cover what the documentation means by "whitespace". It would seem logical that it would be where Chararacter.isWhitespace is true, but that is not what it means by "whitespace" ..
@user2864740: This answer isn't intended to be a comprehensive analysis of trim, isWhiteSpace etc, or a discussion of ambiguities in the Java docs; it's a straightforward answer to the specific question asked above -- ie, does the trim method remove a single space or multiple spaces?
I know it is not. I down-voted because it fails to point such out, even in passing. In any case, I can't undo my vote unless it's updated (however minimally).
33

From the source code (decompiled) :

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

The two while that you can see mean all the characters whose unicode is below the space character's, at beginning and end, are removed.

Comments

27

When in doubt, write a unit test:

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

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

1 Comment

Ask a new programmer that just learned how to do a System.out.println to do a unit test to see what is the outcome...
26

One thing to point out, though, is that String.trim has a peculiar definition of "whitespace". It does not remove Unicode whitespace, but also removes ASCII control characters that you may not consider whitespace.

This method may be used to trim whitespace from the beginning and end of a string; in fact, it trims all ASCII control characters as well.

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

3 Comments

Seems like a terrible oversight on the designers part .. and the terribly over-technical working of the documentation doesn't help much.
Bravo! You took the simplest question ever asked on StackOverflow and found something intelligent to say about it. You're a credit to the race.
@MarkMcKenna: I keep finding that these supposedly super-simple programming questions (trimming strings, finding file name extensions etc) always have their hidden complexities. That is a bit disillusioning about our craft and tools.
15

See API for String class:

Returns a copy of the string, with leading and trailing whitespace omitted.

Whitespace on both sides is removed:

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"

1 Comment

actually nothing can change the String instance (except some dirty things that could crash VM)
13

Based on the Java docs here, the .trim() replaces '\u0020' which is commonly known as whitespace.

But take note, the '\u00A0' (Unicode NO-BREAK SPACE &nbsp; ) is also seen as a whitespace, and .trim() will NOT remove this. This is especially common in HTML.

To remove it, I use :

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

An example of this problem was discussed here.

1 Comment

Based on the Javadoc it removes leading and trailing whitespace, which includes space, tab, newline carriage return, form feed, ... and which excludes characters that aren't leading or trailing.
8

Example of Java trim() removing spaces:

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

OUTPUT

old = 
 This is a String.


new = This is a String.

Comments

4

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

Note that after getting start and length it calls the substring method of String class.

1 Comment

Where "whitespace" is "characters with values less than or equal to \x20" .. brillant.
3

trim() will remove all leading and trailing blanks. But be aware: Your string isn't changed. trim() will return a new string instance instead.

1 Comment

It will remove all leading and trailing whitespace.
3

If your String input is:

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

Yes, output will be, "abc"; But if your String input is:

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

Output will be 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. This is a piece of my code that slightly optimizes the built in String trim method removing the inner spaces and removes spaces before and after your first and last character in the string. Hope it helps.

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

1 Comment

First couple of statements in this answer are plain wrong, output will not be "abc". Perhaps you forgot to .trim() in the System.out.println(a); ?
2

It will remove all spaces on both the sides.

Comments

2

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

if a string sSomething = "xxxxx", where x stand for white spaces, sSomething.trim() will return an empty string.

if a string sSomething = "xxAxx", where x stand for white spaces, sSomething.trim() will return A.

if sSomething ="xxSomethingxxxxAndSomethingxElsexxx", sSomething.trim() will return SomethingxxxxAndSomethingxElse, notice that the number of x between words is not altered.

If you want a neat packeted string combine trim() with regex as shown in this post: How to remove duplicate white spaces in string using Java?.

Order is meaningless for the result but trim() first would be more efficient. Hope it helps.

Comments

2

To keep only one instance for the String, you could use the following.

str = "  Hello   ";

or

str = str.trim();

Then the value of the str String, will be str = "Hello"

Comments

0

Trim() works for both sides.

Comments

0

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

Comments

0

If you want to check what will do some method, you can use BeanShell. It is a scripting language designed to be as close to Java as possible. Generally speaking it is interpreted Java with some relaxations. Another option of this kind is Groovy language. Both these scripting languages provide convenient Read-Eval-Print loop know from interpreted languages. So you can run console and just type:

"     content     ".trim();

You'll see "content" as a result after pressing Enter (or Ctrl+R in Groovy console).

1 Comment

So to understand a method in Java he should go learn an entirely new language. Really?
0
String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");

4 Comments

This isn't related to the question.
@Mark but accidentally it was what I was looking for when I opened this question...
It is also pointless. trim() already does what the repkaceAll() would do, if there was anything left for it to do.
@EJP the replaceAll would also replace whitespaces IN the string with a single space, while trim would only handle leading and trailing spaces

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.