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
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_howto_remove_whitespace.asp
Java How To Remove Whitespace from a String
The trim() method only removes whitespace from the start and end of the string. String text = " Java "; String trimmed = text.trim(); System.out.println(trimmed); // "Java" ... Explanation: trim() is useful when you only want to clean up leading ...
Discussions

[Java] Removing extra whitespace from a string and counting words in a string?
look into trim() and split() methods. More on reddit.com
๐ŸŒ r/learnprogramming
11
7
February 22, 2012
How to remove zero width space (zwsp) (Unicode U+200B) from a text file?
If you just want to get rid of them, use a competent text editor, such as EditPad. Or are you looking for a way to do it via programming? More on reddit.com
๐ŸŒ r/learnprogramming
9
7
July 25, 2014
How to convert list to string without brackets or spaces?

join method of strings.

','.join(test)

Although, since you've got integers in that list, you'll have to convert them to strings.

','.join(str(num) for num in test)
More on reddit.com
๐ŸŒ r/learnpython
3
1
May 3, 2017
[Java] Ignoring case, spaces, and punctuation while comparing strings
I know you can remove spaces from a string by doing something like: .replaceAll("\s",""); I think there might also be something you can use instead of \s to remove all non-word characters. More on reddit.com
๐ŸŒ r/learnprogramming
7
1
March 11, 2013
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ remove-spaces-from-a-given-string
Remove spaces from a given string - GeeksforGeeks
April 11, 2026 - #include <stdio.h> #include <string.h> char* removeSpaces(char s[]) { int n = strlen(s); for (int i = 0; i < n; i++) { if (s[i] == ' ') { // shift all characters to the left // starting from current index for (int j = i; j < n - 1; j++) { s[j] = s[j + 1]; } n--; i--; } } // return string up to new valid length // without spaces s[n] = '\0'; return s; } int main() { char s[] = "g eeks for ge eeks "; printf("%s", removeSpaces(s)); return 0; } Java ยท
๐ŸŒ
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 - Usually, when we need to deal with a string like myString in Java, we often face these two requirements: removing all whitespace characters from the given string -> โ€œIamawonderfulString!โ€ ยท replacing consecutive whitespace characters with a single space, and removing all leading and trailing whitespace characters -> โ€œI am a wonderful String !โ€
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ remove-whitespaces
Java Program to Remove All Whitespaces from a String
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(); } } Output ยท Enter the string J av a- P rog ram m ing Original String: J av a- P rog ram m ing Final String: Java-Programming ยท In the above example, we have used the Java Scanner to take input from the user.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ remove whitespace from string in java
Remove Whitespace From String in Java - Scaler Topics
January 6, 2024 - These spaces are eliminated once the method trim() is called and the output is printed. ... Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching โ‚น23L. ... The strip() method was introduced in Java 11. It also removes leading and trailing spaces present in the string.
Find elsewhere
๐ŸŒ
Medium
rameshfadatare.medium.com โ€บ java-program-to-remove-all-whitespace-from-a-string-819ccfb84997
Java Program to Remove All Whitespace from a String | by Ramesh Fadatare | Medium
December 13, 2024 - The replaceAll() method is used with the regular expression \\s to match all whitespace characters (spaces, tabs, newlines, etc.) and replace them with an empty string "". The program prints the string without any whitespace using ...
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ trimming-extra-spaces-from-text-in-java-b20af8a84b6d
Trimming Extra Spaces from Text in Java | Medium
July 30, 2025 - Trimming text in Java usually starts with the two most common methods built right into the String class: trim() and strip(). Both are meant to clean up extra spaces at the beginning and end of a string, but they work differently once you look closer.
๐ŸŒ
Java Code Geeks
javacodegeeks.com โ€บ home โ€บ core java
Different ways to remove Spaces from String In Java - Java Code Geeks
August 4, 2020 - It means we cannot modify a string, hence all the methods returns new string with all the transformations. trim() is the most commonly used method by java developers for removing leading and trailing spaces.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ how-to-remove-all-white-spaces-from-a-string-in-java
How to Remove all White Spaces from a String in Java? - GeeksforGeeks
In Java, to remove all white spaces from a String, there are several ways like using replaceAll() or manual iteration over characters.
Published ย  July 11, 2025
๐ŸŒ
Techndeck
techndeck.com โ€บ java-how-to-remove-whitespaces-from-a-string-simplest-example
Java - How to remove 'WHITESPACES' from a String? - Simplest Example - Techndeck
January 12, 2023 - public class Remove_Whitespaces_from_String_Java_Example { public static void main(String[] args) { String str = " Here we have a string with whitespaces "; // Remove leading and trailing whitespaces String strWithoutLeadingandTrailingSpaces = str.strip(); // Remove all whitespaces String strWithoutAnySpace = str.replaceAll("\\s", ""); System.out.println("String without Leading & Trailing spaces: "+strWithoutLeadingandTrailingSpaces); System.out.println("String without any space: "+strWithoutAnySpace); } }
๐ŸŒ
Java String
javastring.net โ€บ home โ€บ how to remove whitespace from string in java
How to Remove Whitespace from String in Java
August 9, 2019 - We can also write a simple utility method to remove all the whitespaces from the string. Itโ€™s just for coding practice and you should adhere to the standard methods to replace whitespaces from the string. package net.javastring.strings; public class JavaRemoveWhitespaceFromString { public static void main(String[] args) { String str2 = "Hello\n\r\t Java"; // using replaceAll() System.out.println(str2.replaceAll("\\s", "")); // using custom method str2 = removeAllWhitespaces(str2); System.out.println(str2); } private static String removeAllWhitespaces(String str2) { char[] chars = str2.toCharArray(); StringBuilder sb = new StringBuilder(); for(int i = 0; i < chars.length; i++) { if(!Character.isWhitespace(chars[i])) { sb.append(chars[i]); } } return sb.toString(); } }
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ java โ€บ examples โ€บ remove-all-whitespaces-from-a-string
Java Program to Remove All Whitespaces from a String | Vultr Docs
December 16, 2024 - This method reads each character in the string and replaces each substring that matches the regex with the given replacement. Utilize the regex \\s+ which matches one or more whitespace characters.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-remove-white-spaces-from-string-using-regex
Java - Remove White Spaces from String using Regex - GeeksforGeeks
July 23, 2025 - // Java Program to remove // white spaces using regex import java.util.regex.*; // Main Class public class RegexWhiteSpaceExampleOne { // Main method public static void main(String[] args) { // Input String String inputString = " Welcome to GeeksForGeeks "; // Remove white spaces using regex String outputString = inputString.replaceAll("\\s+", ""); // Display the results System.out.println("Input String: \"" + inputString + "\""); System.out.println("Output String: \"" + outputString + "\""); } }
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-remove-whitespaces-from-a-string-in-java
How to remove whitespaces from a string in Java
We have two methods to remove all the whitespaces from the string. In Java, we can use the built-in replaceAll() method to remove all the whitespaces of the given string.
๐ŸŒ
Medium
medium.com โ€บ @azizmarzouki โ€บ trim-vs-strip-in-java-9481243db3a7
Trim() vs Strip() in Java
October 23, 2024 - "; // Using strip() to remove leading and trailing whitespace String strippedString = originalString.strip(); System.out.println("Original: '" + originalString + "'"); // Output: ' Hello, World!
๐ŸŒ
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 - ". This string contains various whitespace characters, including spaces and a newline character. To remove all whitespace characters from the string, we use the replaceAll() method along with the regular expression pattern "\\s".
๐ŸŒ
Conventional Commits
conventionalcommits.org โ€บ en โ€บ v1.0.0
Conventional Commits
A description MUST immediately follow the colon and space after the type/scope prefix. The description is a short summary of the code changes, e.g., fix: array parsing issue when multiple spaces were contained in string.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ guide to splitting a string by whitespace in java
Guide to Splitting a String by Whitespace in Java | Baeldung
December 9, 2025 - The trim() method removes any leading or trailing whitespace that might otherwise create empty strings in our result, while \\s+ efficiently handles any sequence of whitespace characters as delimiters, regardless of their specific type or quantity.
๐ŸŒ
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);
}