Remove Whitespaces from a String in Java

In this post, we will discuss how to remove whitespaces from a String in Java.


 

A character is called a whitespace character in Java if and only if Character.isWhitespace(char) returns true. The most commonly used whitespace characters are \n ,\t ,\r and a space. The regular-expression pattern for whitespace characters is \s. Using this pattern in a regex, we can either replace consecutive whitespace by a single space or remove all whitespace from the input string.

 

1. Replacing consecutive whitespaces by 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.

 

Download   Run Code

Output:

Techie Delight

 

2. Removing all whitespaces

 

2.1. Regex

 

Download   Run Code

Output:

TechieDelight

 

2.2. Apache Commons Lang

We can also use StringUtils utility class from Apache commons lang which provides deleteWhitespace() method that deletes all whitespaces from a String, as defined by Character.isWhitespace(char).

 

Download   Run Code

Output:

TechieDelight

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz