tags:

views:

388

answers:

10

If I've got string like that:

"     content     ".

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

+2  A: 

It will remove all spaces on both the sides.

Ravia
+2  A: 

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

tangens
+11  A: 

All of them.

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

LukeH
+2  A: 

Trim() works for both sides.

ZeissS
+2  A: 

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.

subtenante
+4  A: 

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 fails

dfa
+7  A: 

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"
Juha Syrjälä
A: 

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

fastcodejava
+1  A: 

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).

Rorick
+4  A: 

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).

Thilo