Java – Remove all white spaces from a string

Learn to write a java program to remove all the white spaces from a given string. It may not be needed in real world applications, but it certainly can be asked in interviews to check your knowledge and reasoning.

1. Java program to remove all white-spaces using regex

Best way to find all whitespaces and replace them with empty string is using regular expressions.

A white space is denoted with "\\s" in regex. All we have to find all such occurrences and replace with empty string.

Use "\\s+" if there are more than one consecutive whitespaces. It matches one or many whitespaces.

To perform this search and replace in string, we can use String.replaceAll() method.

public class Main 
{
    public static void main(String[] args) 
    {
        String sentence = " how to do in java ";
        System.out.println("Original sentence: " + sentence);

        sentence = sentence.replaceAll("\\s+", "");

        System.out.println("After replacement: " + sentence);
    }
}

Program output.

Original sentence:  how to do in java 
After replacement: howtodoinjava

2. Remove all whitespaces using Character.isWhitespace()

Another easy way to do this search and replace is by iterating over all characters of the string. Determine is current char is white space or printable character.

Append all printable characters in a string and omit all white spaces. The resulted string will be free from all white spaces.

public class Main 
{
	public static void main(String[] args) 
	{
		String sentence = " how to do in java ";
		System.out.println("Original sentence: " + sentence);

		sentence = sentence.codePoints()
				.filter(c -> !Character.isWhitespace(c))
				.collect(StringBuilder::new, 
							StringBuilder::appendCodePoint, 
							StringBuilder::append).toString();

		System.out.println("After replacement: " + sentence);
	}
}

Program output.

Original sentence:  how to do in java 
After replacement: howtodoinjava

Drop me your questions in comments.

Happy Learning !!

Read More :

Java remove extra white spaces between words in String
Java remove leading whitespaces from String
Java remove trailing whitespaces from String
Java remove leading and trailing white spaces
What is whitespace character

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.