In Java, strings are used to store textual data. Oftentimes, the textual data stored is inconsistently spaced due to user error. Such inconsistency of whitespaces is problematic in use cases like string comparison, validation, formatting, and many more. In Java, developers can use multiple static and built-in methods for removing whitespaces from a string.
This article discusses basic usage to advanced techniques using various functions for removing whitespaces in a string in Java.
Quick Outline
- Remove Whitespaces Using String Class
- Remove Whitespaces Using Character Class
- Remove Whitespaces Using StringUtils Class
- Remove Whitespaces Using Custom Logi
Remove Whitespaces Using String Class
The String class in Java offers multiple static and built-in functions to manipulate strings such as equals(), concat(), equalsIgnoreCase(), toString(), etc. Developers can directly invoke different methods of String class for removing spaces from a string as discussed below:
Method 1: Removing Whitespaces Using String.trim()
The trim() function removes leading and trailing whitespaces from the given string and returns a modified string. This method is directly called by the string variable and accepts no parameter. The following is the syntax of the trim() method:
public String trim()
Example: How to Use String.trim() Method in Java?
First, create a string variable “str1” and initialize it:
String str1=" This is JavaBeat.net ";
The print statements display the comparison between the original string and the modified string returned by the trim() method:
System.out.println("Original String is : " + str1);
System.out.println("String after removing spaces : " + str1.trim());
Complete Code & Output
Note: Null pointer exception is thrown if a null string calls the trim() method.
Method 2: Removing WhiteSpaces Using String.strip()
The strip() method of the String class removes starting and ending whitespaces from the string. A modified string is returned by this method of the String class. The syntax is as follows:
public String strip()
Example: How to Use String.strip() Method in Java?
In the following code, a string variable “str1” is created and initialized. The “\t” is a special character which is used to insert 8 tabular spaces:
String str1 ="\t This is JavaBeat. net";
Both the original string and the modified string returned by the strip() method are printed for comparison using the print statement:
System.out.println("Original String is : " + str1);
System.out.println("String after removing spaces is : " + str1.strip());
Complete Code & Output
Comparison of String.trim() and String.strip() Methods
Both the strip() and trim() methods in Java remove excess leading and trailing spaces. So how do they differ? The strip() method is “Unicode-aware” meaning that this method is capable of removing spaces that are inserted using the Unicode. On the other hand, the trim() method cannot remove the whitespaces inserted using Unicode. The practical demonstration of this difference is given as follows:
Example: Difference Between String.trim() and String.strip() Method in Java:
A string variable “str1” is initialized with the respective value. The “\u2002” is the Unicode for inserting whitespaces:
String str1 = '\u2002'+ "Welcome to JavaBeat.net";
The following print statements display the comparison between the original string and the string returned by the trim() and strip() method:
System.out.println("Original String is : " + str1);
System.out.println("By using the trim method: " + str1.trim());
System.out.println("By using the strip method: " + str1.strip());
Complete Code & Output
Method 3: Removing Whitespaces Using the String.stripLeading()
The stripLeading() method of the String class removes the leading whitespaces from a string. This variant of the strip() method does not remove any trailing whitespaces from the given string and returns a modified string. Given below is the basic syntax of the stripLeading() method:
public String stripLeading()
Example: How to Use String.stripLeading() Method in Java?
First, create a string variable “str1” with the leading and trailing spaces inserted:
String str1 = " Remove the leading spaces ";
The two print statements display the original string and the modified string returned by the stripLeading() method after removing the leading whitespaces:
System.out.println("Original String is : " + str1);
System.out.println("Output = "+ str1.stripLeading());
Complete Code & Output
Method 4: Removing Whitespaces Using String.stripTrailing()
The stripTrailing() method in Java removes the excessive trailing whitespaces while the leading whitespaces remain the same. Given below is the syntax of the stripTrailing() method:
public String stripTrailing()
Example: How to Use the stripTrailing() Method in Java?
The string variable named “str1” is created and initialized with the following value:
String str1 = " Remove the ending spaces ";
The first print statement displays the original string on the console. The “\”” is a special character used to print inverted commas to mark the starting and ending of the string. The modified string returned by the stripTrailing() method is also printed in the following manner:
System.out.println("Original String is : " + "\"" + str1 + "\"");
System.out.println("Output is : " + "\"" + str1.stripTrailing() + "\"");
Complete Code & Output
Method 5: Removing Whitespaces Using the String.replace()
Another method of the String class that is used to remove whitespaces from the string is the “replace()” method. The replace method replaces the particular character with the specified characters within the string. You can also use this method to remove the whitespaces from the string by using the following syntax:
public String replace(oldString, newString)
Example: How to Use the String.replace() Method in Java?
A string variable “str1” is created with the following value:
String str1=" Let's learn JAVA ";
A comparison of the original string and the modified strings is displayed using the print statement. The double spaces within the string are replaced by the single whitespaces. Similarly, the single whitespaces are removed from the string:
System.out.println("Original String output : " + str1);
System.out.println("Remove Double Spaces : " + str1.replace(" " , " "));
System.out.println("Remove Single Spaces : " + str1.replace(" ", ""));
Complete Code & Output
Method 6: Removing Whitespaces Using the String.replaceAll()
The replaceAll() method works similar to the replace() method. It replaces the specific string that matches the given regex with another string as mentioned in the syntax given below:
public String replaceAll(String regex, String newString)
Example 1: How to Use the String.replaceAll() Method in Java?
The string “str1” is declared and initialized within the main() method:
String str1=" Learn about JAVA ";
The comparison of the original and modified string is displayed. The “\”” is a special character which is used to print strings within the inverted commas. In the replaceAll() method, the regex “\\s+” specifies all the white spaces within the string. All the whitespaces within the string will be removed by using the given code:
System.out.println("Original String : " + "\"" +str1 + "\"");
System.out.println("Modified String : " +"\""+ str1.replaceAll("\\s+", "") + "\"");
Complete Code & Output
Example 2: How to Use String.replaceAll() Method for Removing the Leading Whitespaces in Java?
The replaceAll() method can remove the leading whitespaces within a string. For this purpose, the regex will be modified which is demonstrated in the following example:
First, a string variable “str1” is created with the respective values:
String str1=" Learn about JAVA ";
Within the second print statement, the replaceAll() method is called. The regex “^\\s+” specifies that only the leading entries are to be replaced. The second argument “” specifies that all the leading whitespaces are to be replaced with no spaces:
System.out.println("Original String : " + "\"" +str1 + "\"");
//removing the spaces at the start of the string
System.out.println("Remove Leading Space : " + "\"" + str1.replaceAll("^\\s+", "") + "\"" );
Complete Code & Output
Example 3: How to Use String.replaceAll() Method For Removing the Trailing Whitespaces in Java?
Similarly, the replaceAll() method is also used to remove the trailing or ending spaces within the string. The following example provides a practical demonstration of this functionality:
String str1=" Learn about JAVA ";
System.out.println("Original String : " + "\"" +str1 + "\"");
//removing the spaces at the end of the string
System.out.println("Remove Trailing Space : " + "\"" + str1.replaceAll("\\s+$", "") + "\"" );
In the given code, a string variable “str1” is declared and initialized. The first print statement displays the original string. Similarly, the second print statement displays the modified string within the inverted commas returned by the replaceAll() method
Complete Code & Output
Remove Whitespaces Using Character Class
The Character class in Java also offers multiple functions for working with the characters. The “isWhitespace()” method determines if the character is whitespace or not. The following example shows the usage of this method to remove whitespaces from the string:
Example: How to Use Character.isWhitespace() Method in Java?
Two strings “str1” and “newString” are declared and initialized with the given values:
String str1=" Learn about JAVA ", newString="";
The for loop iterates over the string and terminates when the integer variable “i” exceeds the length of the string. Inside the for loop, a character variable “ch” is created. It stores the current character of “str1” returned by the charAt() method. The if-statement executes when the isWhitespace() returns true for the current character. Otherwise, the else statement is executed:
for(int i=0; i<str1.length();i++)
{
char ch=str1.charAt(i);
if(Character.isWhitespace(ch))
{
continue;
}
else
{
newString+=ch;
}
}
/s
The output is displayed on the console:
System.out.println("Output is = " + newString);
Complete Code & Output
Remove Whitespaces Using StringUtils Class
The StringUtils class is a utility class provided by the “Apache Common Lang” library. This class provides multiple static pre-defined functions for accessing and manipulating strings. To remove whitespaces from the string, the normalizeSpace() and deleteWhitespace() methods of the StringUtils class can be used.
Prerequisite
To use any method of the StringUtills class, first, add the following dependency in the “pom.xml” file of the Maven project or the “build.gradle” file of the Gradle project:
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
</dependencies>
Now you can import and use the StringUtils class without any hassles.
Method 1: Removing Whitespaces Using StringUtils.normalizeSpace()
The normalizeSpace() of the StringUtils class is a static built-in method that returns a modified string after removing the leading and trailing whitespaces. The excessive whitespaces are removed and replaced by single spaces. The example given below demonstrates the usage of this method:
Example: How to Use the normalizeSpace() Method in Java?
Use the following line of code to include the StringUtils class:
import org.apache.commons.lang3.StringUtils;
Inside the main() method, declare and initialize a string variable “str1” with the respective value. The output returned by the normalizeSpace() method is a modified string which is displayed on the console:
String str1=" Let's Learn Java";
System.out.println("Output is : " + "\"" + StringUtils.normalizeSpace(str1)+ "\"");
Complete Code & Output
Method 2: Removing Whitespaces Using StringUtils.deleteWhitespace()
As the name suggests, the deleteWhitespace() method removes all the whitespaces and returns a modified string. It is a pre-defined static method and is directly invoked using the StringUtils class.
Example: How to Use the deleteWhitespace() Method in Java?
To utilize the deleteWhitespace() method of the StringUtils class, use the following line of code:
import org.apache.commons.lang3.StringUtils;
The “str1” is declared and initialized. Inside the print statement, the deleteWhitespace() method is invoked which returns a modified string. The string is then printed within the inverted commas using the special character “\””:
String str1=" Let's Learn Java";
System.out.println("Output is : " + "\"" + StringUtils.deleteWhitespace(str1)+ "\"");
Complete Code & Output
Remove WhiteSpaces Using Custom Logic
The whitespaces within a string can also be removed by implementing custom logic or by using user-defined functions.
Example: How to Remove WhiteSpaces From a String Using Custom Logic?
In the following line of code, two strings are declared and initialized with the respective values. The “str1” is the string from which the whitespaces are to be removed. The “newStr” will store the modified string:
String str1=" Learn about JAVA ";
String newStr="";
The for loop continues to iterate over the elements of the string until the integer “i” exceeds the length of the string. The if-statement checks if the character at the current index returned by charAt() is equivalent to whitespace or not. If the character matches, the “continue” statement skips the character. On the other hand, if it is a character other than whitespaces, it is added to the “newStr” to form a string without whitespaces:
for (int i=0; i<str1.length();i++)
{
if(str1.charAt(i)==' ') {
continue;
}
else
{
newString+=str1.charAt(i);
}
}
Finally, the output is displayed on the console:
System.out.println("Output : " + newString);
Complete Code & Output
This concludes the working of different methods for removing whitespaces from a string in Java.
Conclusion
In Java, removing whitespaces from strings is a crucial task when it comes to string comparison or validation, etc. You can either use pre-defined instances of different public classes in Java or use your custom functions. The whitespaces in strings can be removed by using the trim(), strip(), or replaceAll() method of the String class. Similarly, the isWhitespace() method of the Character class also serves this functionality.
Furthermore, developers can also use the normalizeSpace() and deleteWhitespace() methods of the StringUtils class. In this guide, different functions ranging from the basic to the advanced level are demonstrated to remove whitespaces from a string in Java.