deleteWhitespace
is a static method of the StringUtils
class that removes all the whitespace characters in a given string.
A character is determined as a whitespace character through the method Character.isWhitespace().
StringUtils
is defined in the Apache Commons Lang
package. Apache Commons Lang
can be added 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>
Note: For other versions of the commons-lang package, refer to the Maven Repository.
You can import the StringUtils
class as follows.
import org.apache.commons.lang3.StringUtils;
public static String deleteWhitespace(String str)
String str
- the string to delete all the whitespace characters from.The function returns a modified String
without whitespace characters.
In the code below, we test the deleteWhitespace
function on different inputs.
If the argument passed is
null
, then the function returnsnull
.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args){System.out.println(StringUtils.deleteWhitespace(""));System.out.println(StringUtils.deleteWhitespace(" hello educative "));System.out.println(StringUtils.deleteWhitespace("hello\teducative"));System.out.println(StringUtils.deleteWhitespace("hello\teducative\n"));}}
The output of the code above is as follows:
helloeducative
helloeducative
helloeducative
The first line in the output is an empty string.