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 pointU+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'sCharacter.isWhitespaceaccepts, 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:
- Declare a
Stringnamedresultbelows. The cleaned text is still a string. - Assign it
s.strip(). The two spaces on each side are removed, soresultholds"hello"andsis 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 abooleanwithout creating a new string. - Only whitespace goes. Quotes, commas and other visible punctuation at the edges stay where they are. A
nullreference cannot be stripped at all: callingstrip()on it throws aNullPointerException. - 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 oldertrim()removes only characters up to the space character.