st.replaceAll("\\s+","") removes all whitespaces and non-visible characters (e.g., tab, \n).


st.replaceAll("\\s+","") and st.replaceAll("\\s","") produce the same result.

The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one.


Assign the value to a variable, if not used directly:

st = st.replaceAll("\\s+","")
Answer from Gursel Koca on Stack Overflow
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › removing whitespace from string in java
8 Methods to Remove Whitespace From String in Java
June 25, 2025 - To remove whitespace from a string in Java without using the replace() method, you can iterate through each character of the string and append non-whitespace characters to a StringBuilder. Finally, convert the StringBuilder to a string.
People also ask

How do you remove all whitespace from a string in Java, including tabs?
To remove every whitespace character—including tabs (\t), spaces, and newlines—from a Java string, apply replaceAll("\\s", ""). This is especially useful when cleaning input data for validation, encryption, or transmission where extra characters may interfere.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › removing whitespace from string in java
8 Methods to Remove Whitespace From String in Java
How to remove whitespace from the beginning and end of a string in Java?
To remove whitespace from both ends of a string in Java, use the trim() method. It eliminates leading and trailing spaces but does not affect spaces in between. This is ideal when cleaning up user inputs or text from external sources.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › removing whitespace from string in java
8 Methods to Remove Whitespace From String in Java
How can I remove all whitespace from a Java string using Java Streams?
Using Java 8+ Streams, convert the string to a character stream and filter out whitespace with Character.isWhitespace(c). Then collect the result into a new string. This method is clean, modern, and useful for more functional programming styles.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › removing whitespace from string in java
8 Methods to Remove Whitespace From String in Java
🌐
W3Schools
w3schools.com › java › java_howto_remove_whitespace.asp
Java How To Remove Whitespace from a String
Explanation: trim() is useful when you only want to clean up leading and trailing spaces, but it will not touch spaces inside the string. If you want to remove all spaces, tabs, and newlines in a string, use replaceAll() with a regular expression.
🌐
Javatpoint
javatpoint.com › java-program-to-remove-all-white-spaces-from-a-string
Java Program to remove all white spaces from a string - javatpoint
Java Program to remove all white spaces from a string with method signature and examples of concat, compare, touppercase, tolowercase, trim, length, equals, split, string charat in java etc.
🌐
HowToDoInJava
howtodoinjava.com › java-examples › remove-all-white-spaces-from-string
Java - Remove All White Spaces from a String
November 14, 2022 - Simple and easy-to-follow free tutorials on Core Java, Spring, Spring Boot, Maven, JPA, Hibernate, JUnit, Python and other popular libraries.
🌐
Programiz
programiz.com › java-programming › examples › remove-whitespaces
Java Program to Remove All Whitespaces from a String
Then, we replace it with "" (empty string literal). import java.util.Scanner; class Main { public static void main(String[] args) { // create an object of Scanner Scanner sc = new Scanner(System.in); System.out.println("Enter the string"); // take the input String input = sc.nextLine(); System.out.println("Original String: " + input); // remove white spaces input = input.replaceAll("\\s", ""); System.out.println("Final String: " + input); sc.close(); } }
Find elsewhere
Top answer
1 of 3
3

There are two flavors of replace() - one that takes chars and one that takes Strings. You are using the char type, and that's why you can't specify a "nothing" char.

Use the String verison:

gtg = gtg.replace("\t", "");

Notice also the bug I corrected there: your code replaces chars from the original string over and over, so only the last replace will be effected.


You could just code this instead:

public static String removeWhitespace(String s) {
    return s.replaceAll("\\s", ""); // use regex
}
2 of 3
1

Try this code,

public class Main {
    public static void main(String[] args) throws Exception {
        String s = " Test example    hello string    replace  enjoy   hh ";
        System.out.println("Original String             : "+s);
        s = s.replace(" ", "");
        System.out.println("Final String Without Spaces : "+s);
    }
}

Output :

Original String             :  Test example    hello string    replace  enjoy   hh                                                                         
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh 

Another way by using char array :

public class Main {
    public static void main(String[] args) throws Exception {
        String s = " Test example    hello string    replace  enjoy   hh ";
        System.out.println("Original String             : "+s);
        String ss = removeWhitespace(s);
        System.out.println("Final String Without Spaces : "+ss);
      
    } 
    
    public static String removeWhitespace(String s) {
        char[] charArray = s.toCharArray();
        String gtg = "";
        
        for(int i =0; i<charArray.length; i++){                
            if ((charArray[i] != ' ') && (charArray[i] != '\t') &&(charArray[i] != '\n')) {
                gtg = gtg + charArray[i];
            }
        }    
        return gtg;
    }
}

Output :

Original String             :  Test example    hello string    replace  enjoy   hh                                                                         
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh
🌐
Baeldung
baeldung.com › home › java › java string › remove whitespace from a string in java
Remove Whitespace From a String in Java | Baeldung
August 13, 2024 - Next, we’ll address two approaches for each case: using the handy replaceAll() method from the String class, and the StringUtils class from the widely used Apache Commons Lang3 library.
🌐
Quora
quora.com › How-do-you-eliminate-spaces-from-a-string-in-Java
How to eliminate spaces from a string in Java - Quora
Answer (1 of 2): O̲n̲e̲ ̲w̲a̲y̲ ̲i̲s̲ ̲t̲o̲ ̲u̲s̲e̲ ̲t̲h̲e̲ ̲`̲r̲e̲pl̲a̲c̲e̲`̲ ̲me̲t̲h̲o̲d̲:̲ ̲`̲y̲o̲u̲r̲S̲t̲r̲i̲n̲g̲ .̲r̲ep̲l̲a̲c̲e̲(̲"̲ "̲ ̲,̲ ̲"̲"̲)̲`̲ ̲s̲w̲a̲p̲s̲ ̲a̲l̲l̲ ̲s̲p̲a̲c̲e̲s ̲w̲i̲t̲h̲ ...
🌐
Reddit
reddit.com › r/learnprogramming › [java] removing extra whitespace from a string and counting words in a string?
r/learnprogramming on Reddit: [Java] Removing extra whitespace from a string and counting words in a string?
February 22, 2012 -

Hello all,
I am a college student taking my first programming class, and need help with some parts of an assignment, and was hoping I could get some help here. In the program we're writing, the user is prompted for a string, and then we must delete all extra whitespace between the words (so no trim), as well as making sure the sentence meets the minimum word count.

Here is what I have written for the word counter, but it seems really bulky, and it also doesn't count words if they are proceeded by a comma or other (valid) non-letter character:

//Error for a sentence with too few words.
int wordCountStart = 0;
int wordCount = 1;
char b = sentence.charAt(wordCountStart);
while (wordCountStart < sentence.length())
{
  while ((b == ' ') || (b == '(') || (b == ')') || (b == '.') || (b == '?') || (b == '!') || (b == ',') || (b == '/') || (b == '"') || (b == '[') || (b == ']') || (b == '-') || (b == ':') || (b == ';') ||(b == '\''))
  {
    wordCountStart ++;
    if (wordCountStart == sentence.length()) break;
    b = sentence.charAt(wordCountStart);
  }
  while (Character.isLetter(b))
  {
    wordCountStart ++;
    if (wordCountStart == sentence.length()) break;
    b = sentence.charAt(wordCountStart);
  }
  if (b == ' ')
  {
    wordCount ++;
  }
  
}
if (wordCount < 7)
{
  JOptionPane.showMessageDialog(null, "Your sentence needs to contain at least 7 words.", "Error", JOptionPane.ERROR_MESSAGE);
  System.exit(0);
}
🌐
javathinking
javathinking.com › blog › remove-whitespace-from-a-string-in-java
How to Remove Whitespace From a String in Java: A Comprehensive Guide — javathinking.com
Cumbersome for removing all whitespace (requires multiple replace() calls). The String.trim() method removes leading and trailing whitespace (ASCII whitespace: space, tab, newline, etc.) but leaves internal whitespace intact.
🌐
TutorialsPoint
tutorialspoint.com › how-to-remove-all-whitespace-from-string-in-java
How to remove the white spaces in Java
June 24, 2025 - Python TechnologiesDatabasesComputer ProgrammingWeb DevelopmentJava TechnologiesComputer ScienceMobile DevelopmentBig Data & AnalyticsMicrosoft TechnologiesDevOpsLatest TechnologiesMachine LearningDigital MarketingSoftware QualityManagement Tutorials View All Categories ... Following example demonstrates how to remove the white spaces with the help matcher.replaceAll(stringname) method of Util.regex.Pattern class. import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] argv) { String str = "This is a Java program.
🌐
Sololearn
sololearn.com › en › Discuss › 1622775 › how-to-remove-spaces-in-a-string-without-using-any-inbuilt-methods-or-function-in-java
How to remove spaces in a string without using any inbuilt methods or function in java | Sololearn: Learn to code for FREE!
December 16, 2018 - find below the code snippets as per the algorithm by KrOW String s1="Hello World !!"; String s2=""; int l=s1.length(); for(int i=0;i<l;i++) { if(s1.charAt(i)!=' ') s2=s2+s1.charAt(i); else continue; } System.out.print(s2);
🌐
Scaler
scaler.com › home › topics › remove whitespace from string in java
Remove Whitespace From String in Java - Scaler Topics
January 6, 2024 - In contrast to s1, which contains ... printed. ... Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L. ... The strip() method was introduced in Java 11....
🌐
Level Up Lunch
leveluplunch.com › java › examples › remove-whitespace-from-string
Remove whitespace from string | Level Up Lunch
November 16, 2013 - @Test public void remove_all_whitespace_apache_commons () { String madJug = "Madison Java User Group"; String removeAllSpaces = StringUtils.deleteWhitespace(madJug); assertEquals("MadisonJavaUserGroup", removeAllSpaces); }
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › remove-spaces-from-a-given-string
Remove spaces from a given string - GeeksforGeeks
April 11, 2026 - public class GfG { static String removeSpaces(String s) { // replace all spaces with empty string s = s.replace(" ", ""); return s; } public static void main(String[] args) { String s = "g eeks for ge eeks "; System.out.print(removeSpaces(s)); } }
🌐
javathinking
javathinking.com › blog › removing-whitespace-from-strings-in-java
How to Remove All Whitespace from Strings in Java: Fixing trim() and replaceAll Pitfalls
Avoid replaceAll(" ", "") or replaceAll("\\s", ""): They miss Unicode whitespace. Use replaceAll("\\p{IsWhite_Space}", "") for a concise, Unicode-aware solution. Use iteration with Character.isWhitespace() for performance-critical code. Leverage StringUtils.deleteWhitespace() if you’re already using Apache Commons. ... By avoiding these pitfalls and using the right tools, you’ll ensure your Java strings are clean and whitespace-free.