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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of