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

8 comments on “Java – How to remove spaces in between the String

  1. 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]

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

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

    Reply
  4. 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.

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

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

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *