Java Programing laungage

java.util Projects

java.util Project 1

Removing duplicate white spaces

In this programming tutorials page, we shall be learn how to remove all white spaces from the given string by using the regular expressions. This page gives us an example for the best description about the way of removing all the duplicate white spaces from the given string.

Previous Home Next

Code Description

Pattern pattern = Pattern.compile("\\s+")

This code is used to create an instance of the Pattern class which is compile the text or regular expression i.e. used to search in the specified string.

Matcher matcher = pattern.matcher(string)

This code is used to create an instance of the Matcher class which is used to match the compiled character in the string which is passed through the matcher() method of the above created instance of the Pattern class.


The find() method of the instance of Matcher class is used for checking the compiled string matches in the specified string or not. Is is return the Boolean value either true or false.

matcher.replaceAll(" ")

This method is used to return the whole fresh string after replacing all duplicate white spaces by the help of the single space and then it crate a fresh string and return the whole string.


package r4r;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class removewhitespace {
public static void main(String[] args) throws IOException{
BufferedReader br = 
new BufferedReader(new InputStreamReader(;
("Enter string in which you want to search: ");
String str = br.readLine();
Pattern pattern = Pattern.compile("\\s+");
Matcher matcher = pattern.matcher(str);
boolean check = matcher.find();
String str1 = matcher.replaceAll(" ");
 ("String after removing all duplicate white spaces:"+ str1);

Previous Home Next