How to remove all white spaces from a String in Java?
Given a string with white spaces, the task is to remove all white spaces from a string using Java built-in methods.
Examples:
Input: str = " Beginner for Beginner "
Output: w3wiki
Input: str = " A Computer Science Portal"
Output: AComputerSciencePortal
Method 1: Using string class in built functions
To remove all white spaces from String, use the replaceAll() method of the String class with two arguments, which is
replaceAll("\\s", "");
where \\s is a single space in unicode
Example:
Java
class BlankSpace { public static void main(String[] args) { String str = " Beginner for Beginner " ; // Call the replaceAll() method str = str.replaceAll( "\\s" , "" ); System.out.println(str); } } |
Output
w3wiki
Method 2: Using Character Class in built functions
In this case, we are going to declare a new string and then simply add every character one by one ignoring the whiteSpace for that we will use Character.isWhitespace(char c).
Java
// Importing required libraries import java.io.*; import java.util.*; // Class class GFG { // Main driver method public static void main(String[] args) { String str = " Beginner for Beginner " ; String op = "" ; for ( int i = 0 ; i < str.length(); i++) { char ch = str.charAt(i); // Checking whether is white space or not if (!Character.isWhitespace(ch)) { op += ch; } } System.out.println(op); } } |
Output
w3wiki
Method 3: Using String.replace() method:
Java
// Importing required libraries import java.io.*; import java.util.*; // Class class GFG { // Main driver method public static void main(String[] args) { String str = " Beginner for Beginner " ; String op = str.replace( " " , "" ); System.out.println(op); } } |
Output
w3wiki
Method 4 : Using Java 8 Streams:
Java
// Importing required libraries import java.io.*; import java.util.*; import java.util.stream.Collectors; // Class class GFG { // Main driver method public static void main(String[] args) { String str = " Beginner for Beginner " ; String op = str.chars() .filter(c -> !Character.isWhitespace(c)) .mapToObj(c -> String.valueOf(( char ) c)) .collect(Collectors.joining()); System.out.println(op); } } |
Output
w3wiki