Saturday, October 25, 2025
HomeData Modelling & AIHow to remove all white spaces from a String in Java?

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

neveropen

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

neveropen
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS