How to remove extra spaces between words in Java

Extra spaces in a String can be removed using the replaceAll method with a regular expression.

Syntax:

example = example.replaceAll(" +", " ");

Example:

This example first create the String to clean, the String has character separated by un unknown number of spaces. The expression matches as many spaces as possible and replace them with one space. The output is then written in System.out.

public class RemoveConsecutiveSpace {

	public static void main(String[] argv){
		
		String example = "A    B C   D         E";
		
		example = example.replaceAll(" +", " ");
		
		System.out.print( "Cleaned String: " + example);
	}
}

The output will be:

	
Cleaned String: A B C D E

References:

Pattern