Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

trim

People also ask

Does trim remove all spaces Java?

To remove leading and trailing spaces in Java, use the trim() method.

Does trim remove all spaces?

Trim() Removes all leading and trailing white-space characters from the current string.

What does string trim () do in Java?

Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.

Does trim remove \n in Java?

trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string. Show activity on this post. Bro, @JohnB It will remove all the new line character in between the string as well.


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:

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

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


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