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:

Download  Run Code

Output:

Techie Delight

2. Removing all whitespaces

We can do this in two ways:

⮚ Regex

Download  Run Code

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).

Download Code

Output:

TechieDelight

That’s all about removing whitespace from a Java String.