Skip to content
TheChatArchiveThe Chat Archive
ClaudeClaude Opus 4.6· anthropicHugging Face Frontier Reasoning Traces

Write a Java program to remove all whitespace from a string.

  1. User

    Write a Java program to remove all whitespace from a string.

  2. Claude 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 replaceAll method, 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.

    1. Regex \\s: This pattern matches any whitespace character (spaces, tabs, newlines).
    2. 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