Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 07 Sep, 2022
Improve Article
Save Article

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

To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e.

replaceAll("\\s", "");
where \\s is a single space in unicode

Program: 

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
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!