In this Java tutorial, you will learn how to remove whitespace characters from a string. The examples cover removing all whitespace, removing only line breaks, removing leading and trailing whitespace, reducing repeated whitespace between words, and removing whitespace without using replace().
Ways to remove whitespace from a Java String
The correct method depends on which whitespace you want to remove. Java can remove every whitespace character, remove only spaces or line breaks, trim whitespace from the two ends, or reduce repeated whitespace to a single space.
| Requirement | Common Java approach |
|---|---|
| Remove all whitespace | replaceAll("\\s+", "") |
| Remove ordinary space characters only | replace(" ", "") |
| Remove whitespace at the beginning and end | strip() or trim() |
| Reduce repeated whitespace between words | strip().replaceAll("\\s+", " ") |
Remove whitespace without replace() or a regular expression | Loop through the characters and test them with Character.isWhitespace() |
replace() performs literal replacement, while replaceAll() treats its first argument as a regular expression. For whitespace patterns such as \\s+, use replaceAll().
Remove all whitespace characters from a Java String
A regular expression is useful when spaces, tabs, line feeds, carriage returns, or other regex whitespace characters may appear in different positions. In a Java string literal, the regular expression \s is commonly written as "\\s". Adding + matches one or more consecutive whitespace characters.
String result = text.replaceAll("\\s+", "");
This removes matching whitespace from the beginning, middle, and end of the string. It also joins words that were separated only by whitespace, so use it only when that is the intended result.
Java examples for removing whitespace from a String
1. Remove all whitespace characters in string
In this example, we will remove all the white-spaces in a string using String.replace() function.
/**
* Java Example Program, to remove white spaces from string
*/
public class RemoveSpaces {
public static void main(String[] args) {
String str1 = "Hi! Good morning.\
Have a good day. ";
//remove white spaces
String resultStr = str1.replaceAll("\\\s", "");
System.out.print(resultStr);
}
}
Run the program. All white spaces in the string: spaces between the words, leading spaces, trailing spaces, and all spaces shall be removed from the string.
Hi!Goodmorning.Haveagoodday.
When you write new code for the same requirement, a clear form is replaceAll("\\s+", ""). The + lets one regex match consume a run of adjacent whitespace characters.
2. Remove all new-line characters from string
In this example, we will remove all the new-line characters, but not worry about other white space characters.
/**
* Java Example Program, to remove white spaces from string
*/
public class RemoveSpaces {
public static void main(String[] args) {
String str1 = "Hi! Good morning.\
Have a good day. ";
//remove white spaces
String resultStr = str1.replaceAll("\
", "");
System.out.print(resultStr);
}
}
Run the program.
Hi! Good morning.Have a good day.
The new-line character between the string has been removed.
Remove only regular space characters with String.replace()
If you want to remove only the ordinary space character and leave tabs or line breaks untouched, you do not need a regular expression. Use String.replace() with a literal space and an empty string.
public class RemoveSpaces {
public static void main(String[] args) {
String text = "Java removes spaces";
String result = text.replace(" ", "");
System.out.println(result);
}
}
Javaremovesspaces
This is different from replaceAll("\\s+", ""). The literal replace() call above targets only the space character supplied to it; it does not define a general whitespace pattern.
Remove leading and trailing whitespace without deleting spaces between words
If the requirement is only to clean the beginning and end of a string, do not remove every whitespace character. In Java 11 and later, strip() is designed for leading and trailing Unicode-aware whitespace. The older trim() method removes leading and trailing characters whose values are at or below U+0020.
public class RemoveEdgeWhitespace {
public static void main(String[] args) {
String text = " Java String ";
String result = text.strip();
System.out.println("[" + result + "]");
}
}
[Java String]
The space between Java and String remains because strip() works on the edges rather than removing whitespace throughout the string.
Remove extra spaces between words while keeping one separator
Removing all whitespace is often too aggressive for normal text. If the goal is to clean extra spaces, tabs, or line breaks while keeping the words separated, first remove whitespace from the edges and then replace each run of internal whitespace with one ordinary space.
public class NormalizeWhitespace {
public static void main(String[] args) {
String text = " Java String\twhitespace ";
String result = text.strip().replaceAll("\\s+", " ");
System.out.println(result);
}
}
Java String whitespace
This approach preserves one separator between words instead of joining the words together.
Remove line breaks while preserving spaces and tabs
When only line separators should be removed, match line breaks rather than all whitespace. Java regular expressions provide \R for a line-break sequence.
public class RemoveLineBreaks {
public static void main(String[] args) {
String text = "First line\nSecond line\r\nThird line";
String result = text.replaceAll("\\R", "");
System.out.println(result);
}
}
First lineSecond lineThird line
If a line break should become a word separator instead of disappearing, replace it with " " rather than an empty string.
Remove whitespace from a Java String without replace() or replaceAll()
You can remove whitespace without replacement methods by scanning the string and copying only the characters you want to keep. Character.isWhitespace() makes the intent explicit and is useful when you need custom character-by-character rules.
public class RemoveWhitespaceWithoutReplace {
public static void main(String[] args) {
String text = "Java \t String\nExample";
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (!Character.isWhitespace(ch)) {
result.append(ch);
}
}
System.out.println(result);
}
}
JavaStringExample
This version removes characters that Java classifies as whitespace and avoids regular-expression processing.
Choosing between replace(), replaceAll(), strip(), and trim()
- Use
replace(" ", "")when only literal space characters should be removed. - Use
replaceAll("\\s+", "")when matching whitespace throughout the string is the requirement. - Use
strip()in Java 11 or later when only leading and trailing whitespace should be removed using Java’s Unicode-aware whitespace definition. - Use
trim()when you specifically need its older leading-and-trailing character rule or are working with code that targets older Java versions. - Use
strip().replaceAll("\\s+", " ")when repeated whitespace should be normalized rather than removed completely. - Use
Character.isWhitespace()with a loop when you need custom whitespace filtering withoutreplace()or regular expressions.
Java String whitespace removal summary
In this Java Tutorial, we learned how to remove white space characters from a string using regular expression and escape characters of white space characters and String.replaceAll() function.
For new code, choose the operation based on the exact requirement: remove every whitespace character with replaceAll(), remove only literal spaces with replace(), clean only the edges with strip() or trim(), or normalize repeated whitespace when the words must remain separated.
TutorialKart.com