Remove All White Spaces from a String in Java


Write a Java Program to remove all white spaces from a string.

Click Here to View the Solution!
public class WhitespacesRemover {
         public static void main(String[] args) {
         String sent = "T    his is t h  e  b  est     web s  ite.";
         System.out.println("Original sentence: " + sent);
         sent = sent.replaceAll("\\s", "");
         System.out.println("After replacement: " + sent);
Click Here to View the Output!
Original sentence: T    his is t h  e  b  est     web s  ite.
 After replacement: Thisisthebestwebsite.
Click Here to View the Explanation!
  • In this program, for omitting and replacing all the occurrences of the white space characters in a string, the string method called replaceAll() has been utilized.
  • In order to encompass all forms of white space characters, a regular expression \\s has been used so that spaces, tabs, new line characters etc. are all inclusive to this approach. After that, these chosen characters are replaced with empty strings “” to eliminate any space character present in the string.
%d bloggers like this: