Java Basics Examples
Java Tutorial
Java Useful Resources
Selected Reading
© 2013 TutorialsPoint.COM
|
Java Examples - Removing White Spaces
Advertisements
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.
|
Advertisements
|
|
|
Advertisement
Advertisements
|
|