Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Edwin Paul C
8 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
2 years ago

Thanks for your help

komal momin
9 years ago

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

G.Lee
9 years ago

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

Binoy Kumar Baranwal
10 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
11 years ago

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

António Santos
12 years ago

This is it.
Thank you

Amol
12 years ago

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