Introduction
Removing whitespaces from strings is a common requirement in data processing, validation, and text formatting. Java provides multiple methods to accomplish this task, each with different performance characteristics and use cases.
Method 1: replaceAll() with Regex
The most concise approach uses regular expressions.
public class RemoveWhitespacesRegex {
public static void main(String[] args) {
String text = "Hello World Java";
// Remove all whitespaces
String result = text.replaceAll("\\s+", "");
System.out.println(result);
// Remove leading and trailing whitespaces only
String trimmed = text.replaceAll("^\\s+|\\s+$", "");
System.out.println(trimmed);
}
}
Output
HelloWorldJava
Hello World Java
Regex Patterns Explained
\\s+– Matches one or more whitespace characters (spaces, tabs, newlines, etc.)\\s– Matches a single whitespace character^\\s+|\\s+$– Matches leading or trailing whitespaces\\s{2,}– Matches two or more consecutive whitespace characters
Examples
String input = " Hello World ";
// Remove all whitespaces
System.out.println(input.replaceAll("\\s+", ""));
// Replace multiple whitespaces with a single space
System.out.println(input.replaceAll("\\s+", " "));
// Remove only tab characters
System.out.println(input.replaceAll("\\t", ""));
// Remove only newline characters
System.out.println(input.replaceAll("\\n", ""));
Output
HelloWorld
Hello World
Hello World
Hello World
Method 2: replace() Method
A simple approach without regular expressions.
public class RemoveWhitespacesReplace {
public static void main(String[] args) {
String text = "Hello World Java";
// Remove spaces only
String result = text.replace(" ", "");
System.out.println(result);
// Chain replacements
String cleaned = text.replace(" ", "")
.replace("\t", "")
.replace("\n", "");
System.out.println(cleaned);
}
}
Output
HelloWorldJava
HelloWorldJava
Advantages
- No regular expression overhead.
- Faster for simple space removal.
- Easy to read.
Disadvantages
- Removes only exact characters.
- Requires multiple calls for different whitespace characters.
Method 3: Using Apache Commons Lang
Apache Commons Lang provides a convenient utility method.
import org.apache.commons.lang3.StringUtils;
public class RemoveWhitespacesCommons {
public static void main(String[] args) {
String text = "Hello World";
String result = StringUtils.deleteWhitespace(text);
System.out.println(result);
}
}
Output
HelloWorld
Advantages
- Very simple API.
- Removes all whitespace characters.
- Suitable when Apache Commons Lang is already included in the project.
Disadvantages
- Requires an external dependency.
Method 4: Manual Loop Approach
Iterate through each character and skip whitespace characters.
public class RemoveWhitespacesLoop {
public static String removeWhitespaces(String input) {
StringBuilder result = new StringBuilder();
for (char ch : input.toCharArray()) {
if (!Character.isWhitespace(ch)) {
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(removeWhitespaces("Hello World"));
}
}
Output
HelloWorld
Advantages
- No regular expressions.
- Efficient for large strings.
- Uses
Character.isWhitespace()to remove all whitespace types.
Disadvantages
- More code than
replaceAll()orreplace().
Method 5: Streams API
A modern Java 8+ functional programming approach.
public class RemoveWhitespacesStream {
public static void main(String[] args) {
String text = "Hello World Java";
String result = text.chars()
.filter(ch -> !Character.isWhitespace(ch))
.collect(
StringBuilder::new,
(sb, ch) -> sb.append((char) ch),
StringBuilder::append)
.toString();
System.out.println(result);
}
}
Output
HelloWorldJava
Advantages
- Modern functional programming style.
- Easy to extend with additional filtering operations.
Disadvantages
- More verbose.
- Higher overhead than loop-based solutions.
Performance Comparison
| Method | Approximate Time (1 Million Operations) |
|---|---|
replaceAll() |
~150 ms |
replace() |
~50 ms |
| Apache Commons | ~60 ms |
| Manual Loop | ~40 ms |
| Streams API | ~200 ms |
Best Choice: For performance-critical applications, use replace() when removing spaces only or the manual loop when removing all whitespace characters.
Common Use Cases
Case 1: Phone Number Formatting
String phoneNumber = "123 456 7890";
String cleaned = phoneNumber
.replace(" ", "")
.replace("-", "");
System.out.println(cleaned);
Output
1234567890
Case 2: Data Validation
String userInput = " john doe ";
String normalized =
userInput.replaceAll("\\s+", " ").trim();
System.out.println(normalized);
Output
john doe
Case 3: Email Normalization
String email = "user @ example . com";
String cleaned =
email.replaceAll("\\s+", "");
System.out.println(cleaned);
Output
user@example.com
Best Practices
Use replace() for Simple Spaces
String text = "Hello World";
String result = text.replace(" ", "");
Use replaceAll() When Different Whitespace Characters Must Be Removed
String text = "Hello\tWorld\nJava";
String result = text.replaceAll("\\s+", "");
Use trim() When Only Leading and Trailing Whitespace Should Be Removed
String text = " Hello World ";
String result = text.trim();
Handle Null Values Safely
public static String removeWhitespaces(String text) {
if (text == null) {
return "";
}
return text.replaceAll("\\s+", "");
}
Frequently Asked Questions
Q1: What's the difference between \s and \s+?
Answer: \s matches a single whitespace character, while \s+ matches one or more consecutive whitespace characters.
Q2: Does replaceAll() remove all types of whitespace?
Answer: Yes. The \s pattern matches spaces, tabs, newlines, carriage returns, and other Unicode whitespace characters.
Q3: Which method is the fastest?
Answer: replace() is the fastest when removing ordinary spaces. For removing all whitespace characters, the manual loop is also very efficient.
Q4: Can I keep a single space between words?
Answer: Yes.
String result = text.replaceAll("\\s+", " ");
This replaces multiple consecutive whitespace characters with a single space.
Q5: How do I remove only leading and trailing whitespaces?
Answer: Use either:
text.trim();
or
text.replaceAll("^\\s+|\\s+$", "");
Q6: What's the performance impact of regular expressions?
Answer: Regular expressions introduce additional overhead because the pattern must be processed. For simple space removal, replace() or a manual loop is generally faster.
Q7: Can I remove only specific whitespace characters?
Answer: Yes.
- Tabs:
\\t - Newlines:
\\n - Carriage returns:
\\r
Example:
String result = text.replaceAll("\\t", "");
Q8: How do I preserve internal spacing?
Answer: Use:
text.trim();
to remove only leading and trailing whitespace, or
text.replaceAll("\\s+", " ");
to replace multiple internal spaces with a single space.
Q9: Does \s work with Unicode whitespace characters?
Answer: Yes. It matches Unicode whitespace characters supported by Java's regular expression engine.
Q10: What if the string is null?
Answer: Always check for null before processing.
if (text != null) {
text = text.replaceAll("\\s+", "");
}