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
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]
Thanks for your help
Thank you so very much. I always find exactly what I need on your website!
Thank you so much. I’ve found many answers to solve errors in my codes on this website.
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.
Thanks a lot, this code helped me a lot 🙂 ….
This is it.
Thank you
Found here the solution.Exactly what I was searching the internet for …
Thanks