Replace Multiple Spaces with Single Space

This program replaces multiple spaces with single space.

Problem Statement

Write a Java program to replace multiple spaces with single space in string.

Source Code

1 public class RegexReplaceSpaces {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Regex Replace Spaces");
4 String str="Eduinq String Programs";
5 String result=str.replaceAll("\\s+"," ");
6 System.out.println("After replacement: "+result);
7 }
8 }

Program Output

Eduinq Regex Replace Spaces
After replacement: Eduinq String Programs

Explanation

The regex \s+ matches one or more consecutive whitespace characters, and replaceAll() collapses each such run into a single space, demonstrating space normalization.

Quick Links to Explore