Open In App

How to remove all white spaces from a String in Java?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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 = "       Geeks     for    Geeks   "            
Output: GeeksforGeeks

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 = "     Geeks     for Geeks     ";
 
        // Call the replaceAll() method
        str = str.replaceAll("\\s", "");
 
        System.out.println(str);
    }
}


Output

GeeksforGeeks

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 = "    Geeks     for Geeks     ";
        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

GeeksforGeeks

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 = "    Geeks     for Geeks     ";
        String op = str.replace(" ","");
       
        System.out.println(op);
    }
}


Output

GeeksforGeeks

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 = "    Geeks     for Geeks     ";
        String op = str.chars()
        .filter(c -> !Character.isWhitespace(c))
        .mapToObj(c -> String.valueOf((char) c))
        .collect(Collectors.joining());
 
        System.out.println(op);
    }
}


Output

GeeksforGeeks



Last Updated : 02 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads