SoFunction
Updated on 2025-05-19

Java implementation method for removing spaces in strings

In Java, there are many ways to remove spaces in strings. Here are some detailed introductions for you:

1. Use replaceAll method to remove all spaces

replaceAllMethods can replace specific characters in strings based on regular expressions.

use\\sMatch all spaces (including spaces, tabs, newlines, etc.) and replace them with an empty string.

public class RemoveSpaces {
    public static void main(String[] args) {
        String str = "  Hello  World!  ";
        String result = ("\\s", "");
        (result); 
    }
}

In the above code,("\\s", "")Put stringsstrAll spaces in it are replaced with empty strings, thus obtaining the string after removing the spaces.

2. Use the replace method to remove all spaces

replaceMethods can directly replace a character or character sequence in a string with other characters or character sequences.

To remove spaces, replace the space character with an empty string directly.

public class RemoveSpaces {
    public static void main(String[] args) {
        String str = "  Hello  World!  ";
        String result = (" ", "");
        (result); 
    }
}

Here(" ", "")Will put stringsstrReplace all space characters in it with an empty string.

3. Remove the beginning and end spaces of string

If you only need to remove the spaces at the beginning and end of the string, you can use ittrimmethod.

public class RemoveSpaces {
    public static void main(String[] args) {
        String str = "  Hello  World!  ";
        String result = ();
        (result); 
    }
}

()Methods remove stringsstrSpaces at the beginning and end, but the spaces in the middle of the string will not be affected.

4. Use StringBuilder to manually remove spaces

Add non-space characters to each character in the stringStringBuilderIn , a string without spaces is finally constructed.

public class RemoveSpaces {
    public static String removeAllSpaces(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < (); i++) {
            if ((i) != ' ') {
                ((i));
            }
        }
        return ();
    }

    public static void main(String[] args) {
        String str = "  Hello  World!  ";
        String result = removeAllSpaces(str);
        (result); 
    }
}

existremoveAllSpacesIn the method,StringBuilderIterate through the string, add only non-space characters, and finallyStringBuilderConvert to string to return.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.