How to Remove all Spaces from a String in Java

The following Java program removes all space characters from the given string. Please note that this program doesn’t work if you want to remove all whitespaces (not just spaces!) from a string.

// Java Example Program to remove all spaces from a String
public class RemoveSpacesExample {

    public static void main(String[] args) {
        String input = "hello world";
        String output = removeSpaces(input);
        System.out.println(input);
        System.out.println(output);
    }

    // Remove all space characters
    private static String removeSpaces(String input) {
        return input.replaceAll(" ", "");
    }
}

Following Java program removes all whitespaces from the given string. In Java, whitespace includes space, tab, line feed, form feed, etc. The full list of whitespace characters are listed here.

// Java example program to remove all whitespaces from a string
public class RemoveAllWhiteSpaces {

    public static void main(String[] args) {
        String input = "hello world\texample\rwith\twhitespaces";
        String output = removeWhiteSpaces(input);
        System.out.println(input);
        System.out.println(output);
    }

    // Remove all whitespace characters (space, tab, return etc.)
    private static String removeWhiteSpaces(String input) {
        return input.replaceAll("\\s+", "");
    }
}

Finally here is a Java implementation that doesn’t use replaceAll method. In this example we extract all characters to an array and then create a new string from the array ignoring whitespace characters.

// This example Java program removes all whitespaces in a string
public class RemoveWhiteSpaceAlternate {
    public static void main(String[] args) {
        String input = "hello world\texample\rwith\twhitespaces";
        String output = removeWhiteSpaces(input);
        System.out.println(input);
        System.out.println(output);
    }

    // Remove all whitespace characters (space, tab, return etc.)
    private static String removeWhiteSpaces(String input) {
        char[] characters = input.toCharArray();
        StringBuffer buffer = new StringBuffer();
        for(char c:characters) {
            if(!Character.isWhitespace(c)) {
                buffer.append(c);
            }
        }
        return buffer.toString();
    }
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply