GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — String.strip() vs trim() | java.evolved

Home / Strings / String.strip() vs trim()
Strings Beginner

String.strip() vs trim()

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Use Unicode-aware stripping with strip(), stripLeading(), stripTrailing().

Strings
Code Comparison
✕ Java 8
// trim() only removes ASCII whitespace
// (chars <= U+0020)
String clean = str.trim();
✓ Java 11+
// strip() removes all Unicode whitespace
String clean = str.strip();
String left  = str.stripLeading();
String right = str.stripTrailing();
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
🌐

Unicode-correct

Handles all whitespace characters from every script.

🎯

Directional

stripLeading() and stripTrailing() for one-sided trimming.

🛡️

Fewer bugs

No surprise whitespace left behind in international text.

Old Approach
trim()
Modern Approach
strip()
Since JDK
11
Difficulty
Beginner
JDK Support
String.strip() vs trim()
Available

Widely available since JDK 11 (Sept 2018)

How it works

trim() only removes characters ≤ U+0020 (ASCII control chars and space). strip() uses Character.isWhitespace() which handles Unicode spaces like non-breaking space, ideographic space, etc.

Related Documentation
String.strip() ↗
Proof
View proof source ↗
Related patterns
Strings Beginner

String.formatted()

Java 8
String msg = String.format(
    "Hello %s, you are %d",
    name, age
);
Java 15+
String msg =
    "Hello %s, you are %d"
    .formatted(name, age);
Hover to see modern ➜
JDK 15+ →
Strings Beginner

String.indent() and transform()

Java 8
String[] lines = text.split("\n");
StringBuilder sb = new StringBuilder();
for (String line : lines) {
    sb.append("    ").append(line)
      .append("\n");
}
String indented = sb.toString();
Java 12+
String indented = text.indent(4);

String result = text
    .transform(String::strip)
    .transform(s -> s.replace(" ", "-"));
Hover to see modern ➜
JDK 12+ →
Strings Beginner

String chars as stream

Java 8
for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    if (Character.isDigit(c)) {
        process(c);
    }
}
Java 9+
str.chars()
    .filter(Character::isDigit)
    .forEach(c -> process((char) c));
Hover to see modern ➜
JDK 9+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.