What is StringUtils.normalizeSpace() in Java?
normalizeSpace() is a 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 1String string = " hello-educative\n\r\n";System.out.printf("StringUtils.normalizeSpace('%s') = '%s'", string, StringUtils.normalizeSpace(string));System.out.println();// Example 2string = " 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
- undefined by undefined
- undefined by undefined