Java – Remove All White Spaces from a String

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

See Also: Normalize Extra White Spaces in a String

1. Using Regular Expression

The best way to find all whitespaces and replace them with an 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 them with an 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 the string, we can use String.replaceAll() method.

String sentence = " how to do in java ";
System.out.println("Original sentence: " + sentence);

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

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

Program output.

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

See Also: String strip() – Remove leading and trailing white spaces

2. Using Character.isWhitespace()

Another easy way to do this search and replace is by iterating over all characters of the string.

  • Determine if the current char is white space or printable character.
  • Append all printable characters in the string and omit all white spaces.

The resulted string will be free from all white spaces.

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 the comments.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode