How to trim whitespace from a string
Short answer
The strip() method removes spaces, tabs and line breaks from both ends:
void main() {
String input = " Anna \n";
IO.println("[" + input.strip() + "]");
}Output:
[Anna]Only one side
stripLeading() removes whitespace at the start, stripTrailing() at the end:
void main() {
String text = " hi ";
IO.println("[" + text.stripLeading() + "]");
IO.println("[" + text.stripTrailing() + "]");
}Output:
[hi ]
[ hi]strip or trim
The older trim() removes only characters with codes up to 32 and does not know about Unicode spaces, such as a non-breaking space from Word or HTML. strip() does:
void main() {
String text = " price ";
IO.println("[" + text.trim() + "]");
IO.println("[" + text.strip() + "]");
}Output:
[ price ]
[price]Spaces inside the string
Collapse extra spaces between words with a regular expression:
void main() {
String text = " too many spaces ";
IO.println(text.strip().replaceAll("\\s+", " "));
}Output:
too many spacesCommon mistake
Calling strip() without keeping the result. The method does not change the string, it returns a new one:
void main() {
String name = " Oleg ";
name.strip();
IO.println("[" + name + "]");
}Output:
[ Oleg ]Functions used in this recipe
- String.strip() — Removes any Unicode whitespace from both ends of a string.
- 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.
- String.replaceAll() — Replaces every match of a regular expression.