Java Reference Β· java.lang
Java String.trim() and strip() methods
Reference for Java String.trim(), strip(), stripLeading() and stripTrailing(): removing whitespace, Unicode differences, indent() and common mistakes.
Java can remove whitespace from the ends of a string in two ways. trim() has existed since Java 1.0 and removes anything with a code point of U+0020 or below, which includes spaces, tabs, newlines and control characters. strip() was added in Java 11 and uses Character.isWhitespace(), so it understands Unicode whitespace.
Neither touches whitespace inside the string, and both return a new string (or the same object if nothing needed removing).
" hi ".trim(); // "hi" " hi ".strip(); // "hi" " hi ".stripLeading(); // "hi " " hi ".stripTrailing(); // " hi"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public String trim() public String strip() // Java 11 public String stripLeading() // Java 11 public String stripTrailing() // Java 11 public String stripIndent() // Java 15 public String indent(int n) // Java 12
Returns: a string with leading and/or trailing whitespace removed; the same object if nothing changed.
Throws: nothing; NullPointerException if the receiver is null.
Usage notes
- Prefer
strip()in new code. It follows the Unicode definition of whitespace, which is what users usually expect.trim()removes ASCII control characters but not the no-break space or the ideographic space. - Only the ends. To collapse inner whitespace use
replaceAll("\\s+", " "). - Always keep the result. Strings are immutable;
s.trim();alone has no effect. - Blank check: isBlank() tells you if a string is empty or only whitespace without creating a new one.
- Parse after stripping.
Integer.parseInt(" 42")throwsNumberFormatException;parseInt(" 42".strip())works. stripIndent()removes common leading whitespace from every line, the way text blocks are processed.indent(n)adds or removes spaces on every line and normalizes line endings to\n.- Performance. O(n) at worst and no copy when there is nothing to remove.
- Related char tests:
Character.isWhitespace()for Unicode whitespace,Character.isSpaceChar()for space separators (which includes the no-break space).