What is StringUtils.normalizeSpace() in Java?

normalizeSpace() is a staticthe methods in Java that can be called without creating an object of the class method of the StringUtils class which is used to return the whitespace normalized string by removing the leading and trailing whitespace and then replacing sequences of whitespace characters with a single space.

Importing StringUtils

The definition of StringUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

You can import the StringUtils class as follows:


import org.apache.commons.lang3.StringUtils;

Syntax


public static String normalizeSpace(final String str)

Parameters

  • final String str: The string to normalize whitespace from.

Return value

This method returns a whitespace normalized string.

Code

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main(String[] args) {
// Example 1
String string = " hello-educative\n\r\n";
System.out.printf("StringUtils.normalizeSpace('%s') = '%s'", string, StringUtils.normalizeSpace(string));
System.out.println();
// Example 2
string = " hello educative";
System.out.printf("StringUtils.normalizeSpace('%s') = '%s'", string, StringUtils.normalizeSpace(string));
System.out.println();
}
}

Example 1

  • string = " hello-educative\n\r\n"

The method returns hello-educative after removing all the leading and trailing whitespace characters.

Example 2

  • string = " hello educative"

The method returns hello educative after removing all the leading and trailing whitespace characters and replacing sequences of whitespace characters with a single space.

Output

The output of the code will be as follows:


StringUtils.normalizeSpace('   hello-educative

') = 'hello-educative'
StringUtils.normalizeSpace('   hello     educative') = 'hello educative'

Free Resources

Attributions:
  1. undefined by undefined
  2. undefined by undefined