How To Remove All Whitespaces From a String in Java?

How To Remove All Whitespaces From a String in Java?

Are you curious to know, “How to remove all whitespace from a string in Java“? Well, this article is exclusively written for you.

Whitespaces can cause difficulties when we are manipulating strings in Java. If you’re looking to eliminate those unnecessary gaps and streamline your code, we’ve got you covered. In this article, we will look at several ways to remove all the whitespaces from a String in Java using its built-in functions.

Still, if you have any questions related to removing whitespace or facing any issues while doing your Java homework then you can hire the proficient experts at CodingZap.

First, let’s have a look at Strings in Java.

A String is a class in Java that represents a sequence of characters and is used to store text. It is part of the core Java library and provides numerous methods to manipulate the text stored.

However, Strings in Java are immutable, meaning the character values of a string can never be changed once created. Any manipulation in the content of the String, such as addition, deletion, or rearrangement of the characters, creates a new String and assigns its reference to the desired variable.

An example of String and StringBuilder in Java is as follows:

Code to convert our StringBuilder into a string:

import java.util.*;
public class Main {
public static void main(String[] args){
// Creating two strings
String str1 = "Hello ";
String str2 = new String("World!");
// Creating an empty StringBuilder
StringBuilder sb = new StringBuilder("");
// Copying each character of str1 into the StringBuilder
for(int i=0; i<str1.length(); i++){
sb.append( str1.charAt(i) );
}
// Copying all characters of of str2 into the StringBuilder
sb.append(str2);
// Converting the StringBuilder into a String
String str3 = new String(sb);
System.out.println("String 1: " +str1);
System.out.println("String 2: " +str2);
System.out.println("String 3: " +str3);

Output:

String 1: Hello
String 2: World!
String 3: Hello World!

In the above code, we initialized a string in Java using 2 different methods. However, since strings in Java are immutable, we also created a StringBuilder to demonstrate the process to string concatenation in O(1) time.

We then copied all the characters of str1 into theStringBuilder one at a time. We used the append method to copy all the contents to str2 into our StringBuilder. Finally, we converted our StringBuilder into a string and printed all the strings.

 

What Is Whitespace? Read Below

 

Whitespaces refer to the empty characters of a String that represent spaces between any two characters. Whitespaces are often used to make the content readable and provide better formatting.

However, there are certain scenarios where whitespace is undesirable. Whitespaces prove detrimental in string comparison and searching operations, i.e. when we want to match the contents of 2 strings or find a text in another string but can’t due to unnecessary whitespaces. Whitespaces can also often interfere with file processing or data extraction from a file or a URL.

There are several types of whitespaces, such as an empty character or space, a new line, a tab etc. We’ll look at several ways to remove all the whitespaces from a String in Java using its in-built methods.

Sample input and output are as follows:

INPUT: “ Name: M ax , DO B : 04/ 0 6/ 20 00 “
OUTPUT: “Name:Max,DOB:04/06/2000”
INPUT: “ New Notification Received “
OUTPUT: “NewNotificationReceived”

 

What Are The Methods to Remove All Whitespaces From Any Given String? Read Below

 

Some methods to remove all whitespaces from any given string are as follows:

1) Using the replace() function with space character

The replace() function is present in the String class of Java that allows us to replace
all the matching characters or character sequences with our target value. Also, if you can want to understand this code and the string concept more clearly then you should have a basic understanding of comparing strings in Java, to make learning more easy.

The replace() function is present in the String class of Java that allows us to replace
all the matching characters or character sequences with our target value.

Syntax:

public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)

We will use this function to remove all whitespaces from a string in Java:

Code to remove all whitespaces from a string in Java:

import java.util.*;
public class Main {
public static void main(String[] args)
{
// Original String
String str = " Name: M ax , DO B : 04/ 0 6/ 20 00 ";
// using the replace function
String replaced = str.replace(" ", "");
System.out.println(replaced);
}
}

Output:

Name:Max,DOB:04/06/2000

In this code, we started with the original string str containing whitespace characters.
Using the replace() function, we removed all occurrences of space characters from the original string. We specified a space (” “) as the target to be replaced with an empty string.


The replace() function scans the original string and replaces all space characters with an empty string, effectively removing the whitespace. The resulting string with all whitespaces removed is stored in the variable replaced.


Finally, we printed the replaced string to display the modified string without any whitespaces.

2) Using the replaceAll() function

The replaceAll() function is also present in the String class which is used to replace all occurrences of a specified substring with a new value, like the replace() function.
The difference is that it allows for more advanced pattern matching and replacement since it uses regular expressions to match the pattern or substring to replace it. Replace function will fail if the String has any different whitespace, such as a new line
or a tab.

Syntax:

public String replaceAll(String regex, String replacement)

Code to remove all whitespaces from a String using the replaceAll() function is as follows:

import java.util.*;
public class Main {
public static void main(String[] args)
{
// Original String
String str = " Name: M ax , DO B : 04/ 0 6/ 20 00 ";
str += "\n\n \t Age: \t 23";
// using the replace function
String replaced = str.replace(" ", "");
System.out.println("-> Using the replace function: ");
System.out.println(replaced);
//when using replaceAll(), we use regex "\\s" to match all whitespace
characters
replaced = str.replaceAll("\\s", "");
System.out.println("\n-> Using the replaceAll function:");
System.out.println(replaced);
}
}

Output:

-> Using the replace function:
Name:Max,DOB:04/06/2000
Age: 23
-> Using the replaceAll function:
Name:Max,DOB:04/06/2000Age:23

In the above code, we can observe that the replace function can not detect new lines and tabs if we just use the space character. This proves to be a major drawback of the replace function.

We thus use the replaceAll function, which allows us to use regular expressions for pattern matching.

We provided the regular expression “\\s” to match all whitespace characters, including spaces, tabs, and new lines, and replaced all matched characters with an empty string using replaceAll(“\\s”, “”). The modified string with all whitespaces removed was assigned to the replaced variable again.

3) Using replace() function with chaining

To overcome the limitation of replace function of not being able to detect all the whitespaces, we will explicitly chain all the desired types of whitespaces that need to be removed from our string.

Code to use chain all the types of whitespaces that we wish to remove:

import java.util.*;
public class Main {
public static void main(String[] args)
{
// Original String
String str = " Name: M ax , DO B : 04/ 0 6/ 20 00 ";
str += "\n\n \t Age: \t 23";
// using the replace function with chaining
String replaced = str.replace(" ", "").replace("\t", "").replace("\n", "");
System.out.println(replaced);
}
}

Output:

Name:Max,DOB:04/06/2000Age:23

As observed before, a single replace function call was not sufficient to remove all types of whitepsaces. We thus use the replace() function with chaining. We first called replace(” “, “”) to remove spaces by replacing them with an empty
string.

Then, we chained additional replace() calls to remove tabs (“\t”) and new lines (“\n”) by replacing them with empty strings as well. Each replace() call in the chain removes a specific type of whitespace from the string.

4) Using the split() function

The split() function is present in the String class of Java and is used to split the string into substrings around one or many matching regular expressions.

Syntax:

public String[] split(String regex)

To remove all whitespaces from our string using the split function, we will split our string around the whitespaces and then join all the substrings into a single string.

Code:

import java.util.*;
public class Main {
public static void main(String[] args)
{
// Original String
String str = " Name: M ax , DO B : 04/ 0 6/ 20 00 ";
str += "\n\n \t Age: \t 23";
// Split the string using the whitespace pattern
String[] substrings = str.split("\\s+");
// Join the generated substring
String replaced = String.join("", substrings);
System.out.println(replaced);
}
}

Output:

Name:Max,DOB:04/06/2000Age:23

In the above code, we used the split() function. We split the string str into substrings using the regular expression pattern “\\s+”, which matches one or more whitespace characters.

This pattern effectively splits the string wherever whitespace occurs. The split() function returns an array of substrings obtained by splitting the original string. Each substring is a segment of the string without any whitespace. We stored
these substrings in the substrings array. It is very important to understand an array as printing an array in Java allows us to debug or verify the program wherever necessary.


Next, we used the String.join() function to join the generated substrings back into a single string. We also specified an empty string as the delimiter to indicate that no separator should be inserted between the substrings. We thus obtain a string with all the whitespaces removed.

 

5) Using isWhitespace() function

isWhitespace() is a function in the Character class of Java that determines whether a character is any type of whitespace or not.

Syntax:

public static boolean isWhitespace(char ch)

We will create a new empty StringBuilder. We will then iterate over every character in our string and append all the non-whitespace characters in the StringBuilder. Finally, we will convert the StringBuilder to String and print the output.

If you want to become a successful programmer, then it’s really important for you to have knowledge about strings in other programming languages as well. You can read the article comparing strings in Python to have an idea about strings in all areas of programming.

Code to convert the StringBuilder to String and print the output:

import java.util.*;
public class Main {
public static void main(String[] args)
{
// Original String
String str = " Name: M ax , DO B : 04/ 0 6/ 20 00 ";
str += "\n\n \t Age: \t 23";
// Create a new Stringbuilder
StringBuilder sb = new StringBuilder();
// iterate every character
for (char c : str.toCharArray())
{
if (!Character.isWhitespace(c)) {
// if not a whitespace, append to StringBuilder
sb.append(c);
}
}
// Convert StringBuilder to String
String replaced = sb.toString();
System.out.println(replaced);
}
}

Output:

Name:Max,DOB:04/06/2000Age:23

In this method, we used a StringBuilder to iterate over each character of the original string str, skipping any whitespace characters by checking it with the isWhiteSpace() function of the Character class. We then appended the non-whitespace characters to the StringBuilder. After the iteration, we converted the StringBuilder back to a String and obtained a modified string without any whitespaces in an efficient manner.

 

Conclusion:

 

In this article, we explored different methods to remove whitespaces from a String in Java using built-in functions. We discussed the immutability of Strings and the benefits of using StringBuilder or StringBuffer for multiple manipulations.

We examined various approaches, including using replace() to remove spaces, replaceAll() with regular expressions to remove all whitespace characters; chaining replace() calls for different types of whitespace, splitting the string and joining the substrings, and iterating over each character using isWhitespace() and StringBuilder.

These methods provide flexibility and efficiency in removing whitespaces, improving readability, and enabling further processing of the string.
In conclusion, we examined multiple techniques to remove all whitespaces from a string in Java, providing various options depending on the specific requirements of the task.

hire us for best programming homework help

Leave a Comment

Your email address will not be published. Required fields are marked *