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?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges