Write a Java Program to Remove All Whitespaces from a String

In Java, whitespaces refer to any blank character including spaces, tabs, and newline characters.

Removing all whitespaces from a string can be useful in various situations, such as when dealing with user input that may contain unnecessary spaces or when parsing text data.

Table of Contents


Here’s a Java program to remove all whitespaces from a string:

public class RemoveWhitespace {
    public static void main(String[] args) {
        String input = "   This is a string with spaces   ";

        // Using replaceAll() method to remove all whitespaces
        String output = input.replaceAll("\\s+", "");

        System.out.println("Input string: " + input);
        System.out.println("Output string: " + output);
    }
}

Explanation

  • The program creates a string variable input and assigns it a value of ” This is a string with spaces “.
  • The replaceAll() method is then called on the input string, with the regular expression \\s+ as its argument. This regular expression matches one or more whitespaces.
  • The replaceAll() method replaces all occurrences of the regular expression with an empty string, effectively removing all whitespaces from the input string.
  • The resulting string is stored in a new variable output.
  • Finally, the program prints both the input and output strings using the System.out.println() method.

Note that the regular expression \\s+ matches one or more whitespaces, so it will remove all consecutive whitespaces in the string.

If you only want to remove leading and trailing whitespaces, you can use the trim() method instead:

String input = "   This is a string with spaces   ";
String output = input.trim();

This will remove all leading and trailing whitespaces from the input string, but leave any internal whitespaces intact.


Conclusion

Removing all whitespaces from a string is a common task in Java programming, and it can be easily accomplished using the replaceAll() method with the regular expression \\s+.

Keep in mind that this will remove all consecutive whitespaces, so if you only want to remove leading and trailing whitespaces, use the trim() method instead.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.