String.strip()
Removes any Unicode whitespace from both ends of a string.
Available since: Java 11
Syntax
public String strip()Return value
StringA new string without leading and trailing whitespace.
Examples
Stripping both ends and only one end:
void main() {
String s = " hi ";
IO.println("[" + s.strip() + "]");
IO.println("[" + s.stripLeading() + "]");
IO.println("[" + s.stripTrailing() + "]");
}Output:
[hi]
[hi ]
[ hi]strip() also removes Unicode spaces that trim() keeps:
void main() {
String s = " text ";
IO.println(s.trim().length());
IO.println(s.strip().length());
}Output:
6
4Notes
Whitespace is whatever Character.isWhitespace() returns true for. The non-breaking space is not included and is removed by neither strip() nor trim().
See also
- String.trim() — Removes spaces and control characters from both ends of a string.
- String.isBlank() — Checks whether a string is empty or contains only whitespace.
Related recipes
In the tutorial
- String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.