Start learning free

LESSON 63 OF 344 · STRINGS I

String Strip in Java: strip, trim and Friends

Lesson Read the full explanation

In Java, you can remove leading and trailing whitespace from a string using strip() (Java 11+) or trim():

s.strip()        // removes leading and trailing whitespace (Unicode-aware)
s.trim()         // removes leading and trailing ASCII whitespace
s.stripLeading() // removes only leading whitespace
s.stripTrailing()// removes only trailing whitespace

Here are some examples:

String s = "  hello  ";
System.out.println(s.strip());         // "hello"
System.out.println(s.stripLeading());  // "hello  "
System.out.println(s.stripTrailing()); // "  hello"

These methods return a new String — the original is not modified.


Assignment
Follow the Coding Tutorial and strip whitespace from s!


Hint
Use s.strip() and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    JAVA · STRINGS I

    String Strip in Java, explained

    What stripping does

    Text from the outside world often carries extra whitespace: spaces typed before a name, a newline at the end of a line, tabs copied from a table. Stripping removes whitespace from the beginning and end of a string and leaves everything in the middle alone.

    String s = "  hello  ";
    System.out.println(s.strip());          // "hello"
    System.out.println(s.stripLeading());   // "hello  "
    System.out.println(s.stripTrailing());  // "  hello"
    

    The three methods differ in which ends they clean:

    • strip() removes whitespace at both ends.
    • stripLeading() removes it only at the start.
    • stripTrailing() removes it only at the end.

    All of them were added in Java 11, so they are available in every current version of Java. Whitespace in the middle is never touched: "a b".strip() is still "a b", with both spaces. Removing inner spaces is a job for replace.

    Strings are immutable

    This point trips up many beginners, so it is worth seeing in code.

    Like every String method that seems to modify text, these return a new string. The original keeps its spaces:

    String s = "  hello  ";
    s.strip();                        // result ignored
    System.out.println(s.length());   // 9
    
    String clean = s.strip();
    System.out.println(clean.length());   // 5
    

    The line that calls s.strip() without storing anything has no effect. Save the result in a variable, or reassign s = s.strip().

    strip versus trim

    Java has an older method, trim(), that does almost the same job. The difference is in what each one treats as whitespace:

    • trim() removes every character up to and including the space character, code point U+0020. That covers the space, tab and newline, but also invisible control characters, and it misses other kinds of space, such as the wide Unicode space  .
    • strip() removes every character that Java's Character.isWhitespace accepts, which includes those Unicode spaces.
    String wide = " hi ";
    System.out.println(wide.strip().length());   // 2
    System.out.println(wide.trim().length());    // 4
    

    For ordinary text with plain spaces, both give the same answer. In new code, strip() is the better default, because it matches what people mean by whitespace.

    The lesson's exercise

    The starting code has one variable:

    String s = "  hello  ";
    

    The task is to remove the surrounding whitespace, in one step:

    1. Declare a String named result below s. The cleaned text is still a string.
    2. Assign it s.strip(). The two spaces on each side are removed, so result holds "hello" and s is unchanged.

    The complete code is:

    String s = "  hello  ";
    
    String result = s.strip();
    

    Why it matters in practice

    Comparisons are exact, so invisible whitespace makes equal-looking strings differ:

    String input = "  yes \n";
    System.out.println("yes".equals(input));          // false
    System.out.println("yes".equals(input.strip()));  // true
    

    Stripping user input before comparing or parsing it avoids this kind of bug. It matters for parsing too: Integer.parseInt(" 42") throws a NumberFormatException because of the leading space, while Integer.parseInt(" 42".strip()) works.

    Stripping also works well together with other string methods, because each call returns a string that the next call can use. Stripping before split avoids empty pieces at the edges:

    String line = "  hello world  ";
    System.out.println(line.split(" ").length);          // 4
    System.out.println(line.strip().split(" ").length);  // 2
    

    Without the strip, the two leading spaces produce two empty pieces ahead of hello and world, so the array has four elements. With it, only the two words remain. Chaining reads left to right: raw.strip().toUpperCase() turns " Alice " into "ALICE".

    Gotchas

    • Use the return value. Calling s.strip() alone changes nothing.
    • Only the ends are cleaned. Spaces between words remain.
    • A string of only whitespace becomes empty. " ".strip() is "". To just ask whether a string is empty or whitespace-only, isBlank() gives a boolean without creating a new string.
    • Only whitespace goes. Quotes, commas and other visible punctuation at the edges stay where they are. A null reference cannot be stripped at all: calling strip() on it throws a NullPointerException.
    • Line breaks count as whitespace. "\n\thi \r\n".strip() is "hi".

    Key takeaways

    • strip() removes whitespace from both ends, stripLeading() from the start, stripTrailing() from the end.
    • They return a new string, because strings are immutable.
    • strip() understands Unicode whitespace, while the older trim() removes only characters up to the space character.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free