Java – How to remove spaces in between the String

This article shows how to use regex to remove spaces in between a String.

A string with spaces in between.


  String text = "Hello       World       Java.";

We want to remove the spaces and display it as below:


  Hello World Java.

1. Java regex remove spaces

In Java, we can use regex \\s+ to match whitespace characters, and replaceAll("\\s+", " ") to replace them with a single space.

Regex explanation.


  `\\s` # Matches whitespace characters.
  +     # One or more
StringRemoveSpaces.java

package com.mkyong.regex.string;

public class StringRemoveSpaces {

    public static void main(String[] args) {

        String text = "Hello       World       Java.";

        String result = text.replaceAll("\\s+", " ");

        System.out.println(result);

    }

}

Output

Terminal

Hello World Java.

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-regex/string

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Edwin Paul C
11 years ago

String mysz = ” Hello Java “;
System.out.println(“[“+mysz.trim()+”]”); //Removes space from left and right –> [Hello Java]
System.out.println(“[“+mysz.replaceAll(“\W+”, ” “)+”]”); //Removes space from middle –> [ Hello Java ]
System.out.println(“[“+mysz.replaceAll(“\W+”, ” “).trim()+”]”); ////Removes space from middle, left and right–> [Hello Java]

JDev C
4 years ago

Thanks for your help

komal momin
11 years ago

Thank you so very much. I always find exactly what I need on your website!

G.Lee
12 years ago

Thank you so much. I’ve found many answers to solve errors in my codes on this website.

Binoy Kumar Baranwal
12 years ago

Yes mkYong. You are right.Regular Expression(regex) is rock. I am already working on regex from last 1 year. I got your updates in my mail. That is why I came back here once again.

Thanks.

Tushar Sharma
13 years ago

Thanks a lot, this code helped me a lot 🙂 ….

António Santos
14 years ago

This is it.
Thank you

Amol
14 years ago

Found here the solution.Exactly what I was searching the internet for …
Thanks