How many spaces will Java String.trim() remove? How many spaces will Java String.trim() remove? java java

How many spaces will Java String.trim() remove?


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


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.


When in doubt, write a unit test:

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

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