Sunday, January 26, 2014

How to remove duplicate white spaces in a string?

Source:
public class RemoveDuplicates {
   public static void main(String[] args) {

      String s1 = "This   is      a    string with     spaces.";
      String s2 = s1.replaceAll("\\s+", " ");
      System.out.println(s1);
      System.out.println(s2);
   }
}

Output:
   $ java RemoveDuplicates 
   This   is      a    string with     spaces.
   This is a string with spaces.

Blog Archive