How to Remove All White Spaces from a String in Java
# Removing All White Spaces from a String in Java
In many programming languages, strings are often used to store text-based data. However, strings may sometimes include unwanted whitespace characters (spaces, tabs, newline characters, etc.) that need to be removed in order for the string to be properly processed. Fortunately, Java provides a number of ways to remove these white spaces from strings, making them easier to manipulate. This tutorial will cover how to use the String class’s `replaceAll()`, `replace()`, and `trim()` methods to remove all white space characters from a given string. Additionally, we will discuss how to use an external library such as Apache Commons Lang to achieve the same result.
Worried About Failing Tech Interviews?
Attend our webinar on
"How to nail your next tech interview" and learn
.png)
Hosted By
Ryan Valles
Founder, Interview Kickstart

Our tried & tested strategy for cracking interviews

How FAANG hiring process works

The 4 areas you must prepare for

How you can accelerate your learnings
Register for Webinar
Algorithm:
1. Create a String variable to store the String with whitespaces.
2. Create a String variable to store the new String without whitespaces.
3. Loop through the String variable.
4. For each character in the String variable, check if it is a whitespace.
5. If the character is not a whitespace, append it to the new String variable.
6. If the character is a whitespace, skip it and go to the next character.
7. After the loop is finished, the new String variable contains the String without whitespaces.
Sample Code:
String withWhitespaces = "This is a String with whitespaces";
String withoutWhitespaces = "";
for (int i = 0; i < withWhitespaces.length(); i++) {
char c = withWhitespaces.charAt(i);
if (!Character.isWhitespace(c)) {
withoutWhitespaces += c;
}
}
System.out.println("String without whitespaces: " + withoutWhitespaces);