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
replaceAll
Methods can replace specific characters in strings based on regular expressions.
use\\s
Match 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 stringsstr
All 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
replace
Methods 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 stringsstr
Replace 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 ittrim
method.
public class RemoveSpaces { public static void main(String[] args) { String str = " Hello World! "; String result = (); (result); } }
()
Methods remove stringsstr
Spaces 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 stringStringBuilder
In , 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); } }
existremoveAllSpaces
In the method,StringBuilder
Iterate through the string, add only non-space characters, and finallyStringBuilder
Convert 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.