How to Delete all spaces from String in JAVA

How to Delete all spaces from String in JAVA

·

1 min read

By String method

yourString.replaceAll(" ", "");

By regular expression

yourString.replaceAll("\\p{Z}", "");

Explanation

Most situations, using the string method will be good enough to delete all spaces in String. However, computers have some charsets that represent spaces such as IDEOGRAPHIC SPACE. In this case, use the regular expression to delete all the spaces.

Example

        String yourString = " this is\u3000test ru n";
        System.out.println(yourString);

        String byMethod = yourString.replaceAll(" ", "");
        System.out.println("byMethod: "+byMethod);

        String byRegularExpression = yourString.replaceAll("\\p{Z}", "");
        System.out.println("byRegularExpression: "+byRegularExpression);

Result

 this is test ru n // original String
thisis testrun // by method
thisistestrun // by regular expression