In Java, to remove all white spaces from a String, there are several ways like using replaceAll() or manual iteration over characters. In this article, we will learn how to remove all white spaces from a string in Java.
Example:
We will use the replaceAll() method with the regex pattern "\\s" to remove all whitespaces from a string. This is the most efficient and concise method.
// Java program to remove all white spaces
// from a string using replaceAll() method
class BlankSpace {
public static void main(String[] args) {
String s = " Geeks for Geeks ";
// Call the replaceAll() method to remove all white spaces
s = s.replaceAll("\\s", "");
System.out.println(s);
}
}
Output
GeeksforGeeks
Table of Content
Other Methods to Remove White Spaces from a String
Apart from the simple method mentioned above, there are few more methods available to remove all white spaces from a string in Java.
1. Using Character Class Built-in Function
In this case, we are going to declare a new string and then simply add every character one by one ignoring the white space. For this, we will use Character.isWhitespace(c).
Example:
// Java program to demonstrate how to remove all white spaces from a string
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
String s = " Geeks for Geeks ";
String a = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// Checking whether is white space or not
if (!Character.isWhitespace(c)) {
a += c;
}
}
System.out.println(a);
}
}
Output
GeeksforGeeks
2. Using String.replace() Method
The replace() method replaces all occurrences of a space (" ") in the string with an empty string ("") by effectively removing all white spaces.
Example:
// Java program to demonstrate how to remove all white spaces from a string
// using the String.replace() method
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
String s = " Geeks for Geeks ";
String a = s.replace(" ","");
System.out.println(a);
}
}
Output
GeeksforGeeks
3. Using Java 8 Streams
Java 8 introduced Streams, which can also be used to remove white spaces by filtering characters.
Example:
// Java program to demonstrate how to remove all white spaces from a string
// using Java 8 Streams
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
class GFG {
public static void main(String[] args)
{
String s = " Geeks for Geeks ";
String a = s.chars()
.filter(c -> !Character.isWhitespace(c))
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
System.out.println(a);
}
}
Output
GeeksforGeeks