Thursday, December 13, 2012
How to remove all white space from String in Java - beginning end and between words
String API in Java provides several utility method to remove white space from String in Java, from beginning, end and between words. White space means blank space including tab characters. One of the classic method to remove white space from beginning and end of a string in Java is trim() method, which removes white space from beginning and end. While using trim() method, key thing to remember is that trim() returns a different String object than older one because String is immutable in Java. On the other hand if you want to remove all white spaces from string i.e. white space from beginning, end and between words then you can use replaceAll() method of String and pass regular expression \s to find and replace all white spaces including tab with empty string "". This is the quickest ways of removing all white space from String in Java. Removing white spaces is not only common programming requirement in Java development but also one of the common String Interview question in Java. Once again just remember that every time you modify a String, even if you remove white space it generate a new String and remember to store and use that. In this Java tutorial we will see Java program to remove all white space from String in Java including beginning and end.
Here is Java program which uses standard Java library to remove all white spaces from any String in Java. This program gives example of trim() method to delete white space from beginning as well ad from end. For removing all white space we have used regular expression along with replaceAll() method of String in Java. Regular expression to find white space is \s, which finds all white spaces including tab character.
That's all on How to remove all white space from String in Java, including white space from beginning, end and middle of String. Just to note you can not remove white spaces only from middle of String or between words, because when you use replaceAll("\\s","") it also removes white spaces from beginning and end of String.
Other Java String tutorials you may like