291

Is there a convenience method to strip any leading or trailing spaces from a Java String?

Something like:

String myString = "  keep this  ";
String stripppedString = myString.strip();
System.out.println("no spaces:" + strippedString);

Result:

no spaces:keep this

myString.replace(" ","") would replace the space between keep and this.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Tyler DeWitt
  • 23,366
  • 38
  • 119
  • 196
  • 7
    It's unfortunate, but it means that the answers here were useful to people. I upvoted for that reason only. – Alex D Mar 12 '12 at 08:32
  • 12
    Whilst this may be a duplicate, this is by far a better presented question. If anything, the other should be close as a duplicate of this one. – thecoshman Jan 27 '14 at 11:41
  • 1
    I switched the duplicates because this Q&A has far more views and favorites, and the other Q&A is actually a debugging question. – Radiodef Jul 23 '18 at 14:02
  • 1
    Made an answer with the [solution from JDK/11 API](https://stackoverflow.com/a/51484070/1746118) - **`String.strip`** to this. – Naman Jul 23 '18 at 17:15

8 Answers8

617

You can try the trim() method.

String newString = oldString.trim();

Take a look at javadocs

szedjani
  • 550
  • 2
  • 6
  • 21
woliveirajr
  • 9,433
  • 1
  • 39
  • 49
  • 1
    Works as a backward-compatible replacement for Java 11's String.strip(). I haven't had time to explore the subtle differences. – Josiah Yoder May 14 '20 at 12:53
86

Use String#trim() method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "") for trim both the end.

For left trim:

String leftRemoved = myString.replaceAll("^\\s+", "");

For right trim:

String rightRemoved = myString.replaceAll("\\s+$", "");
Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
34

From the docs:

String.trim();
Richard H
  • 38,037
  • 37
  • 111
  • 138
18

trim() is your choice, but if you want to use replace method -- which might be more flexiable, you can try the following:

String stripppedString = myString.replaceAll("(^ )|( $)", "");
James.Xu
  • 8,249
  • 5
  • 25
  • 36
4

With Java-11 and above, you can make use of the String.strip API to return a string whose value is this string, with all leading and trailing whitespace removed. The javadoc for the same reads :

/**
 * Returns a string whose value is this string, with all leading
 * and trailing {@link Character#isWhitespace(int) white space}
 * removed.
 * <p>
 * If this {@code String} object represents an empty string,
 * or if all code points in this string are
 * {@link Character#isWhitespace(int) white space}, then an empty string
 * is returned.
 * <p>
 * Otherwise, returns a substring of this string beginning with the first
 * code point that is not a {@link Character#isWhitespace(int) white space}
 * up to and including the last code point that is not a
 * {@link Character#isWhitespace(int) white space}.
 * <p>
 * This method may be used to strip
 * {@link Character#isWhitespace(int) white space} from
 * the beginning and end of a string.
 *
 * @return  a string whose value is this string, with all leading
 *          and trailing white space removed
 *
 * @see Character#isWhitespace(int)
 *
 * @since 11
 */
public String strip()

The sample cases for these could be:--

System.out.println("  leading".strip()); // prints "leading"
System.out.println("trailing  ".strip()); // prints "trailing"
System.out.println("  keep this  ".strip()); // prints "keep this"
Naman
  • 27,789
  • 26
  • 218
  • 353
  • ***PS***: Migrating the answer here based on the comments from - https://stackoverflow.com/questions/3796121/how-to-trim-the-whitespace-from-a-string/50631235#comment89931502_50631235 – Naman Jul 23 '18 at 17:12
  • 5
    Also see [*Difference between String trim() and strip() methods in Java 11*](https://stackoverflow.com/q/51266582/2891664). – Radiodef Jul 23 '18 at 17:14
1

To trim specific char, you can use:

String s = s.replaceAll("^(,|\\s)*|(,|\\s)*$", "")

Here will strip leading and trailing space and comma.

Galley
  • 493
  • 6
  • 9
1

s.strip() you can use from java 11 onwards.

s.trim() you can use.

Satya
  • 8,146
  • 9
  • 38
  • 43
-1
private void capitaliseEveryWordInASentence() {

    String mm = "Hello there, this is the cluster";

    String[] words = mm.split(" ");
    String outt = "";

    for (String w : words) {

        outt = outt + Character.toUpperCase(w.charAt(0)) + w.substring(1) + " ";
    }

    System.out.println(outt.trim());
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 18 '22 at 03:26
  • Looks like you're answering a totally different question here. – Federico klez Culloca Jan 20 '22 at 12:10