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?

Jasper
  • 11,590
  • 6
  • 38
  • 55
oneat
  • 10,778
  • 16
  • 52
  • 70
  • 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. – glmxndr Feb 04 '10 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. – Chris Feb 04 '10 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. – glmxndr Feb 04 '10 at 16:43
  • 1
    @skaffman: (c) should be "try it and see", and only then (d) ask on SO. – Mac Aug 25 '13 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. – Jasper Mar 23 '14 at 01:17

17 Answers17

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

David d C e Freitas
  • 7,481
  • 4
  • 58
  • 67
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 1
    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 Nov 30 '13 at 09:17
  • 7
    @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? – LukeH Dec 02 '13 at 01:10
  • 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). – user2864740 Dec 02 '13 at 01:10
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.

glmxndr
  • 45,516
  • 29
  • 93
  • 118
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

Mate Mrše
  • 7,997
  • 10
  • 40
  • 77
dfa
  • 114,442
  • 31
  • 189
  • 228
  • 43
    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... – jaxkodex Aug 13 '13 at 16:43
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).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 3
    Seems like a terrible oversight on the designers part .. and the terribly over-technical working of the documentation doesn't help much. – user2864740 Nov 30 '13 at 09:13
  • 2
    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. – Mark McKenna Mar 20 '14 at 14:01
  • 3
    @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. – Thilo Mar 20 '14 at 23:16
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"
Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
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.

Community
  • 1
  • 1
Britc
  • 623
  • 5
  • 8
  • 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. – user207421 Nov 29 '14 at 08:49
  • Thanks, it helps me allot – Asad Haider Oct 02 '16 at 08:39
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.
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
USB
  • 6,019
  • 15
  • 62
  • 93
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.

Prateek
  • 12,014
  • 12
  • 60
  • 81
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.

tangens
  • 39,095
  • 19
  • 120
  • 139
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);
  }
oink
  • 1,443
  • 2
  • 14
  • 23
Farah Nazifa
  • 909
  • 8
  • 14
  • 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);` ? – Arjan May 19 '16 at 06:47
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"

jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
Angelos P
  • 21
  • 2
2

It will remove all spaces on both the sides.

Ravi Vanapalli
  • 9,805
  • 3
  • 33
  • 43
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.

Community
  • 1
  • 1
rciafardone
  • 125
  • 1
  • 2
  • 10
0
String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");
Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53
MIke
  • 19
0

Trim() works for both sides.

ZeissS
  • 11,867
  • 4
  • 35
  • 50
0

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

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
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).

Rorick
  • 8,857
  • 3
  • 32
  • 37