Java How To - Remove Whitespace from a String
Remove Whitespace from a String
There are two common ways to remove whitespace in Java: using trim()
and using replaceAll()
.
Remove Whitespace at the Beginning and End
The trim()
method only removes whitespace from the start and end of the string.
Example
String text = " Java ";
String trimmed = text.trim();
System.out.println(trimmed); // "Java"
Explanation: trim()
is useful when you only want to clean up leading and trailing spaces, but it will not touch spaces inside the string.
Remove All Whitespace
If you want to remove all spaces, tabs, and newlines in a string, use replaceAll()
with a regular expression.
Example
String text = " Java \t is \n fun ";
String noSpaces = text.replaceAll("\\s+", "");
System.out.println(noSpaces); // "Javaisfun"
Explanation: The regular expression \\s+
matches any whitespace character (spaces, tabs, newlines). Replacing them with an empty string removes all whitespace from the text.