Remove white spaces from a string

Java provides several methods for removing whitespace from strings. trim() strips ASCII whitespace from both ends, while strip(), stripLeading(), and stripTrailing() (Java 11+) are Unicode-aware. For removing whitespace from within a string, replaceAll(\

In this article, we are going to look at how to remove white spaces from a string.

Contents

Common ways to remove white spaces from string

The easiest way to remove white spaces from a string is to call String.trim() method. Note that String.trim() will remove any character whose unicode value is less than or equal to 'U+0020' (the space character).

For example, in below sample code we are removing white spaces from s1 = " Hello " and s2 = " \0 Hello \r", you can see that String.trim() method will remove control characters as well.

Java
public class RemoveWhiteSpaces {

    public static void main(String[] args) {
        String s1 = " Hello ";
        System.out.println("Length of s1 before removing white spaces : " +(s1.length()));
        System.out.println("Length of s1 before after trimming : " +(s1.trim().length()));

        String s2 = " \0 Hello \r";
        System.out.println("Length of s2 before removing white spaces : " +(s2.length()));
        System.out.println("Length of s2 before after trimming : " +(s2.trim().length()));
    }
}
When you run the above code snippet, it will produce the below output.
Output
Length of s1 before removing white spaces : 7 
    Length of s1 before after trimming : 5 
    Length of s2 before removing white spaces : 10 
    Length of s2 before after trimming : 5

To remove white spaces, we can also use String.strip() method. Note that String.strip() method is unicode aware function, so it will not remove control characters.

Java
public class RemoveWhiteSpaces {

    public static void main(String[] args) {
        String s3 = " Hello ";
        System.out.println("Length of s3 before removing white spaces : " +(s3.length()));
        System.out.println("Length of s3 before after stripping : " +(s3.strip().length()));

        String s4 = " \0 Hello \r";
        System.out.println("Length of s4 before removing white spaces : " +(s4.length()));
        System.out.println("Length of s4 before after stripping : " +(s4.strip().length()));
    }
}
When you run the above code snippet, it will produce the below output. As you can see from second string " \0 Hello \r" it did not remove control characters.
Output
Length of s3 before removing white spaces : 7 
    Length of s3 before after stripping : 5 
    Length of s4 before removing white spaces : 10 
    Length of s4 before after stripping : 7

If you want to remove white spaces from the beginning of string you can use String.stripLeading() and to remove trailing spaces you can use String.stripTrailing()

Above example complete source code can be found at Github