Start learning free

LESSON 64 OF 671 · STRINGS I

String Strip / Trim in Java

Lesson

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