In this Java tutorial, you will learn how to replace multiple spaces with a singe space using String.replaceAll() method, with examples.

Replace multiple spaces with single space in Java

To replace multiple spaces with single space in Java, you can find those sub-strings that match more than one subsequent spaces and then replace them with one space.

In this tutorial, we will learn how to replace multiple spaces coming adjacent to each other with a single space.

Examples

1. Replace multiple spaces with single space

In this example, we initialize a string that contains multiple spaces coming next to other spaces. We use regex to match multiple (two or more) spaces and then replace them with a single space.

Example.java

</>
Copy
public class Example {
	public static void main(String[] args) {
		String str1 = "Hi!   Good      morning. Have a      good   day.";
		
		//replace one or more spaces with one space
		String resultStr = str1.replaceAll("[ ]+", " ");
		
		System.out.print(resultStr);
	}
}

The string “[ ]+” is a regular expression representing one or more regular spaces next to each other. It could match with  single space " ", two spaces "  ", three spaces "   ", four spaces "    ", etc.

Run the program. The output shall be as shown below in the console window.

Output

Hi! Good morning. Have a good day.

Conclusion

In this Java Tutorial, we learned how to replace one or more adjacent coming spaces with a single space.