regex

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+<", "><");

  System.out.println(str);

  System.out.println(output);
    }
}

Output:

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

Ilias Tsagklis

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

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

0 Comments
Inline Feedbacks
View all comments
Back to top button