Remove whitespace from a String in Java
This post will discuss how to remove whitespace from a string in Java.
A character is called a whitespace character in Java if and only if Character.isWhitespace(char) method returns true. The most commonly used whitespace characters are \n, \t, \r and space. The regular-expression pattern for whitespace characters is \s. Using this pattern in a regex, we can either replace consecutive whitespace with a single space or remove all whitespace from the input string.
1. Replacing consecutive whitespaces with a single space
The idea is to use the pattern \s+ instead of \s to handle two or more consecutive whitespaces in the input string, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Main { public static void main(String[] args) { String str = "Techie \t \r \n Delight"; // Replace consecutive whitespaces with a single space str = str.replaceAll("\\s+", " "); // or, use the following regex // str = str.replaceAll("\s{2,}", " "); System.out.println(str); } } |
Output:
Techie Delight
2. Removing all whitespaces
We can do this in two ways:
⮚ Regex
|
1 2 3 4 5 6 7 8 9 10 11 12 |
class Main { public static void main(String[] args) { String str = "Techie \t \r \n Delight"; // Remove all whitespaces str = str.replaceAll("\\s", ""); System.out.println(str); } } |
Output:
TechieDelight
⮚ Apache Commons Lang
We can also use the StringUtils utility class from Apache commons-lang, which provides the deleteWhitespace() method that deletes all whitespaces from a string, as defined by Character.isWhitespace(char).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import org.apache.commons.lang3.StringUtils; class Main { public static void main(String[] args) { String str = "Techie \t \r \n Delight"; // delete all whitespaces from a string str = StringUtils.deleteWhitespace(str); System.out.println(str); } } |
Output:
TechieDelight
That’s all about removing whitespace from a Java String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)