How to remove all white spaces in java
To remove all white spaces from a string in Java, you can use the replaceAll
method of the String
class, along with a regular expression that matches any white space character (including spaces, tabs, and line breaks):
String str = " This is a test ";
str = str.replaceAll("\\s", ""); // str is now "Thisisatest"
You can also use the trim
method to remove leading and trailing white spaces from the string:
String str = " This is a test ";
str = str.trim(); // str is now "This is a test"
Keep in mind that the trim
method only removes leading and trailing white spaces, and not white spaces within the string. To remove all white spaces within the string as well, you can use the replaceAll
method with a regular expression as shown above.