View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

8 Methods to Remove Whitespace From String in Java

Updated on 25/06/20258,650 Views

In Java programming, manipulating strings efficiently is a crucial skill. One common task is to remove whitespace from string in Java, eliminating unnecessary spaces, tabs, or line breaks to streamline text processing and optimize memory usage.

In this article, we’ll explore multiple ways to perform whitespace removal in Java using built-in methods like trim(), strip(), stripLeading(), stripTrailing(), and replaceAll(), along with some custom implementations. Let’s dive into the world of whitespace removal in Java with practical and effective techniques.

How to Remove Whitespace From String in Java

In Java, there are multiple approaches to remove whitespace from a string. Let's explore each method in detail:

Method - 1: Using the trim() Method to Remove Whitespace From String in Java

The trim() method is a built-in function in Java that removes leading and trailing whitespace from a string. It trims spaces from both ends of the string, leaving the internal whitespace intact. For example:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";
        String trimmedStr = str.trim();
        System.out.println(trimmedStr); // Output: "Hello, World!"
    }
}

Output:

Hello, World!

In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.

To remove the leading and trailing whitespace from the string, we use the trim() method. The trim() method is a built-in function in Java's String class that eliminates leading and trailing whitespace characters.

We then assign the trimmed string to the variable trimmedStr. Finally, we print the value of trimmedStr to the console using System.out.println(), which will output "Hello, World!".

When you run this Java program, you will see the output "Hello, World!", demonstrating the removal of whitespace from the original string.

Method - 2: Using the strip() Method to Remove Whitespace From String in Java 11

Introduced in Java 11, the strip() method removes leading and trailing whitespace from a string, similar to trim(). However, strip() is more powerful as it can handle Unicode whitespace characters as well. Here's an example:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";
        String strippedStr = str.strip();
        System.out.println(strippedStr); // Output: "Hello, World!"
    }
}

Output:

Hello, World!

This is because the strip() method removes the leading and trailing whitespace from the string " Hello, World! ", resulting in the trimmed string "Hello, World!". The System.out.println() statement prints this trimmed string to the console, displaying "Hello, World!" as the output.

Method - 3: Using the stripLeading() Method to Remove Whitespace From String in Java 11

The stripLeading() method, introduced in Java 11, removes only the leading whitespace from a string, leaving trailing whitespace intact. It also handles Unicode whitespace characters. Here's an example:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";
        String strippedStr = str.stripLeading();
        System.out.println(strippedStr); // Output: "Hello, World!   "
    }
}

Output:

Hello, World!

In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.

To remove only the leading whitespace from the string, we use the stripLeading() method. The stripLeading() method is a built-in function introduced in Java 11 that trims the whitespace from the beginning of the string while leaving the trailing whitespace intact.

We then assign the stripped string to the variable strippedStr. Finally, we print the value of strippedStr to the console using System.out.println(), which will output "Hello, World! ".

Method - 4: Using the stripTrailing() Method to Remove Whitespace From String in Java 11

The stripTrailing() method, introduced in Java 11, removes only the trailing whitespace from a string, leaving the leading whitespace intact. It handles Unicode whitespace characters as well. Here's an example:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";
        String strippedStr = str.stripTrailing();
        System.out.println(strippedStr); // Output: "   Hello, World!"
    }
}

Output:

Hello, World!

In the given code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.

To remove only the trailing whitespace from the string, we use the stripTrailing() method. The stripTrailing() method is a built-in function introduced in Java 11 that trims the whitespace from the end of the string while leaving the leading whitespace intact.

We then assign the stripped string to the variable strippedStr. Finally, we print the value of strippedStr to the console using System.out.println(), which will output " Hello, World!".

Method - 5: Using the replaceAll() Method to Remove Whitespace From String in Java

The replaceAll() method with regular expressions lets you remove all whitespace characters from a string, including spaces, tabs, and line breaks. Here's an example:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, \nWorld!   ";
        String noWhitespaceStr = str.replaceAll("\\s", "");
        System.out.println(noWhitespaceStr); // Output: "Hello,World!"
    }
}

Output:

In the given code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". 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". The "\\s" pattern matches any whitespace character, including spaces, tabs, and newline characters. We replace all occurrences of whitespace with an empty string "".

We then assign the resulting string to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".

Method 6: Using the String Class to Remove Whitespace From String in Java

By combining multiple string class functions, we can remove all whitespace characters from a string. Here's an example:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, \nWorld!   ";
        String noWhitespaceStr = str.replace(" ", "").replace("\t", "").replace("\n", "");
        System.out.println(noWhitespaceStr); // Output: "Hello,World!"
    }
}

Output:

In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". This string contains various whitespace characters, including spaces, tabs, and a newline character.

We use the replace() method multiple times to remove all whitespace characters from the string. We chain the replace() method calls to individually remove spaces, tabs, and newline characters. In each replace() call, we specify the whitespace character to be replaced with an empty string "".

We then assign the resulting string to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".

Method 7: Using the Character Class to Remove Whitespace From String in Java

The Character class in Java provides handy functions to determine if a character is whitespace. By iterating through the characters of a string, we can filter out the whitespace characters. Here's an example:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, \nWorld!   ";
        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (!Character.isWhitespace(c)) {
                sb.append(c);
            }
        }
        String noWhitespaceStr = sb.toString();
        System.out.println(noWhitespaceStr); // Output: "Hello,World!"
    }
}

Output:

In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". This string contains various whitespace characters, including spaces, tabs, and a newline character.

To remove all whitespace characters from the string, we use a StringBuilder to build the resulting string without whitespace. We iterate through each character of the input string using a for loop and check if the character is not a whitespace character using the Character.isWhitespace() method. We append it to the StringBuilder if it's not a whitespace character.

After iterating through all the characters, we convert the StringBuilder to a string using the toString() method and assign it to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".

How to Remove Whitespace from String in Java without Using Replace()

You can use a combination of string manipulation techniques to remove whitespace from a string in Java without using the replace() method. Here's an example approach:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";
        String noWhitespaceStr = removeWhitespace(str);
        System.out.println(noWhitespaceStr); // Output: "Hello,World!"
    }
    
    public static String removeWhitespace(String str) {
        char[] chars = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        
        for (char c : chars) {
            if (!Character.isWhitespace(c)) {
                sb.append(c);
            }
        }
        
        return sb.toString();
    }
}

Output:

Hello, World!

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. This approach avoids direct replacement and produces a new string without whitespace.

Remove Whitespace from Beginning and End of String

To remove whitespace from the beginning and end of a string in Java, you can use the Java trim. The trim() method is a built-in function that eliminates leading and trailing whitespace characters. Here's an example:

public class WhitespaceRemoval {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";
        String trimmedStr = str.trim();
        System.out.println(trimmedStr); // Output: "Hello, World!"
    }
}

In the above code, the string " Hello, World! " contains whitespace characters at the beginning and end.

By applying the trim() method to the string, we remove those leading and trailing whitespace characters. The resulting string, "Hello, World!", is then printed to the console.

Conclusion

Removing whitespace from strings is a common requirement in Java programming. In this article, we explored various methods to achieve efficient string manipulation by removing whitespace. We covered built-in functions like trim(), strip(), stripLeading(), stripTrailing(), and replaceAll(), along with custom implementations using string class functions and the Character class. By utilizing these techniques, you can optimize your code for improved performance and memory usage. So, the next time you encounter whitespace removal in Java, choose the appropriate method based on your specific needs and achieve efficient string manipulation.

FAQs

1. 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.

2. How to remove all spaces from a string in Java?

If you want to remove every space in a Java string, use replace(" ", ""). This method only removes space characters, so tabs and newlines will remain. It’s useful when formatting strings like phone numbers or IDs without extra characters.

3. How can I remove whitespace and newlines from a Java string?

To remove all whitespace characters—including spaces, tabs, and newlines—use replaceAll("\\s+", ""). The \\s+ regex matches every type of whitespace, making this method effective for cleaning up multiline or user-submitted strings before processing or storing them.

4. What is the best way to replace all whitespace in a Java string?

Use the replaceAll("\\s", "") method to target and remove all whitespace types, such as spaces, tabs, and line breaks. It’s a powerful solution when you need a compact version of a string without any formatting-related characters.

5. 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.

6. How to remove space from a string in Java without using trim()?

To remove all spaces without using trim(), use replace(" ", "") to delete only space characters or replaceAll("\\s", "") for all whitespace. This approach is better when you want to clean up the entire string, not just the ends.

7. How to remove spaces from a string in Java after reading input from Scanner?

After reading user input using Scanner.nextLine(), apply input.replaceAll("\\s", "") to strip all whitespace. This ensures the input is clean and formatted consistently, which is crucial for processing user-entered values like usernames or codes.

8. How to remove whitespace from the start of a string in Java only?

Use replaceAll("^\\s+", "") to remove leading whitespace while keeping internal and trailing spaces intact. This method is helpful when formatting outputs where only the starting alignment needs correction, such as in formatted reports or indented strings.

9. 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.

10. How do I remove only trailing whitespace in Java?

To remove whitespace from the end of a string, use replaceAll("\\s+$", ""). In Java 11 or later, you can also use stripTrailing() for better Unicode support. This is helpful for formatting file paths or trimming user messages.

11. How to replace multiple spaces with a single space and trim the string in Java?

First, apply replaceAll(" +", " ") to reduce consecutive spaces to a single space. Then use trim() to remove leading and trailing whitespace. This method is ideal for formatting sentences or user input while preserving readability.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.