Write a Java program to remove all whitespace from a string.
- User
Write a Java program to remove all whitespace from a string.
Assistant
Problem: Write a Java program to remove all whitespace from a string.
Approach: the standard
Let me implement this solution.
Here is the solution using the standard
replaceAllmethod, which is the most efficient and readable way to handle this in Java.Logic
The program uses the
String.replaceAll()method, which takes a Regular Expression (Regex) as the first argument and a Replacement as the second.- Regex
\\s: This pattern matches any whitespace character (spaces, tabs, newlines). - Replacement
"": This replaces the found whitespace with an empty string, effectively deleting it.
Java Program
public class RemoveWhitespace { public static void main(String[] args) { // 1. Define a string containing various types of whitespace // (Normal spaces, tabs \t, and newlines \n) String originalString = "J a v a \t P r o g r a m \n m i n g"; System.out.println("Original String: \"" + originalString + "\""); // 2. Use replaceAll with the regex "\\s" to find whitespace // and replace it with an empty string "" String noWhitespaceString = originalString.replaceAll("\\s", ""); // 3. Print the result System.out.println("String without whitespace: \"" + noWhitespaceString + "\""); } }Output
Original String: "J a v a P r o g r a m m i n g" String without whitespace: "JavaProgramming"Alternative: Without using Regex
If you need to remove whitespace without using Regular Expressions (for example, in a performance-critical loop or a coding challenge), you can use a
StringBuilder:public class RemoveWhitespaceManual { public static void main(String[] args) { String str = "Hello World "; StringBuilder result = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); // If the character is not a whitespace, append it if (!Character.isWhitespace(c)) { result.append(c); } } Syste- Regex