Java Program to Remove All Whitespaces from a String

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Program to Remove All Whitespaces

 public class Whitespaces { public static void main(String[] args) { String sentence = "T his is b ett er."; System.out.println("Original sentence: " + sentence); sentence = sentence.replaceAll("\\s", ""); System.out.println("After replacement: " + sentence); } }

Output

 Original sentence: T his is b ett er. After replacement: Thisisbetter.

In the above program, we use String's replaceAll() method to remove and replace all whitespaces in the string sentence.

To learn more, visit Java String replaceAll().

We've used regular expression \\s that finds all white space characters (tabs, spaces, new line character, etc.) in the string. Then, we replace it with "" (empty string literal).


Example 2: Take string from users and remove the white space

 import java.util.Scanner; class Main { public static void main(String[] args) { // create an object of Scanner Scanner sc = new Scanner(System.in); System.out.println("Enter the string"); // take the input String input = sc.nextLine(); System.out.println("Original String: " + input); // remove white spaces input = input.replaceAll("\\s", ""); System.out.println("Final String: " + input); sc.close(); } }

Output

 Enter the string J av a- P rog ram m ing Original String: J av a- P rog ram m ing Final String: Java-Programming

In the above example, we have used the Java Scanner to take input from the user.

Here, the replaceAll() method replaces all the white spaces from the string.


Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community