Tutorials Point


  Java Basics Examples
  Java Tutorial
  Java Useful Resources
  Selected Reading

© 2011 TutorialsPoint.COM


  Home     References     Discussion Forums     About TP  

Java Examples - Removing White Spaces


previous next AddThis Social Bookmark Button


Problem Description:

How to remove the white spaces?

Solution:

Following example demonstrates how to remove the white spaces with the help matcher.replaceAll(stringname) method of Util.regex.Pattern class.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String[] argv) 
   throws Exception {
      String ExString = "This is a Java program. 
      This is another Java Program.";
      String result=removeDuplicateWhitespace(ExString);
      System.out.println(result);
   }
   public static CharSequence 
   removeDuplicateWhitespace(CharSequence inputStr) {
      String patternStr = "\\s+";
      String replaceStr = " ";
      Pattern pattern = Pattern.compile(patternStr);
      Matcher matcher = pattern.matcher(inputStr);
      return matcher.replaceAll(replaceStr);
   }
}

Result:

The above code sample will produce the following result.

ThisisaJavaprogram.ThisisanotherJavaprogram.


previous next Printer Friendly



  

Advertisement

Online Image Processing

Indian Baby Names