Strip extra spaces in a string

With this example we are going to demonstrate how to strip extra spaces in a String. In short, to strip extra spaces in a String you should:

  • Use a given String with spaces between words.
  • Use replaceAll(String regex, String replacement) API method of String, with a given regular expression. The regular expression is constructed by the white character between the “>” “<” characters. This method replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl).
  • Print the given String and the result String to check the change between the two Strings.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

public class StripSpaces {

    public static void main(String[] args) {

  String str = "<a>test 1</a>    <b>test 2</b> ";

  String output = str.replaceAll(">\s+<", "><");




<a>test 1</a>    <b>test 2</b> 
<a>test 1</a><b>test 2</b> 

This was an example of how to strip extra spaces in a String in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button