Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 07 Nov, 2018

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 replaceAll() method of String class with two arguments, i.e.

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

Program:




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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :