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.
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;
public static String normalizeSpace(final String str)
final String str
: The string to normalize whitespace from.This method returns a whitespace normalized string.
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();}}
string = " hello-educative\n\r\n"
The method returns hello-educative
after removing all the leading and trailing whitespace characters.
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.
The output of the code will be as follows:
StringUtils.normalizeSpace(' hello-educative
') = 'hello-educative'
StringUtils.normalizeSpace(' hello educative') = 'hello educative'
Free Resources