In Java, you can remove all white spaces from a string by using the replaceAll()
method with a regular expression or by manually iterating through the string and omitting the spaces.
Here are a couple of ways to achieve this:
1. Using replaceAll()
with a Regular Expression
The simplest and most efficient way to remove all white spaces is to use the replaceAll()
method with the regex pattern "\\s"
, which matches any whitespace character (spaces, tabs, newlines).
Example Code:
public class RemoveWhiteSpaces {
public static void main(String[] args) {
String input = "Hello World! This is a string with white spaces.";
// Remove all white spaces using replaceAll()
String result = input.replaceAll("\\s", "");
System.out.println("Original String: " + input);
System.out.println("String without white spaces: " + result);
}
}
Explanation:
replaceAll("\\s", "")
: The\\s
is a regex that matches any whitespace character (spaces, tabs, or newlines). ThereplaceAll()
method replaces all occurrences of this pattern with an empty string, effectively removing all white spaces.
Output:
Original String: Hello World! This is a string with white spaces.
String without white spaces: HelloWorld!Thisisastringwithwhitespaces.
2. Using replace()
Method
You can also use the replace()
method if you’re only concerned with space characters (' '
), rather than other types of whitespace (tabs, newlines, etc.).
Example Code:
public class RemoveWhiteSpaces {
public static void main(String[] args) {
String input = "Hello World! This is a string with white spaces.";
// Remove all spaces (only space characters ' ')
String result = input.replace(" ", "");
System.out.println("Original String: " + input);
System.out.println("String without white spaces: " + result);
}
}
Explanation:
replace(" ", "")
: This replaces only space characters (' '
) with an empty string, leaving tabs, newlines, or other white space characters intact.
Output:
Original String: Hello World! This is a string with white spaces.
String without white spaces: HelloWorld!Thisisastringwithwhitespaces.
Conclusion
Using replaceAll("\\s", "")
is more flexible as it removes all types of whitespace characters (spaces, tabs, newlines, etc.), while replace(" ", "")
only removes space characters.
If you need further assistance or want to modify this approach, feel free to reach out to Divi Tech HR Solution (info@divisolutions.in). Don’t forget to like and comment on this blog if it helped!
0 Comments