How to Remove or Trim All White Spaces from a String in Java

Introduction

Removing or trimming all white spaces from a string in Java is a common task that can be useful in various scenarios, such as cleaning user input, formatting data, or preparing strings for further processing. Java provides several methods to achieve this. This blog post will explore different methods in Java to remove or trim all white spaces from a string.

Table of Contents

  1. Using replaceAll()
  2. Using replace()
  3. Using Regular Expressions
  4. Using Apache Commons Lang StringUtils
  5. Complete Example Program
  6. Conclusion

1. Using replaceAll()

The replaceAll() method of the String class can be used to remove all white spaces from a string by using a regular expression.

Example:

public class RemoveWhiteSpaceUsingReplaceAll {
    public static void main(String[] args) {
        String str = "  Hello   World  ";

        // Remove all white spaces using replaceAll()
        String noWhiteSpaceStr = str.replaceAll("\\s+", "");

        System.out.println("Original String: '" + str + "'");
        System.out.println("String without white spaces: '" + noWhiteSpaceStr + "'");
    }
}

Output:

Original String: '  Hello   World  '
String without white spaces: 'HelloWorld'

Explanation:

  • str.replaceAll("\\s+", "") removes all white spaces from the string using the regular expression \\s+, which matches one or more white space characters.

2. Using replace()

The replace() method of the String class can be used to remove all white spaces from a string by replacing each white space character with an empty string.

Example:

public class RemoveWhiteSpaceUsingReplace {
    public static void main(String[] args) {
        String str = "  Hello   World  ";

        // Remove all white spaces using replace()
        String noWhiteSpaceStr = str.replace(" ", "");

        System.out.println("Original String: '" + str + "'");
        System.out.println("String without white spaces: '" + noWhiteSpaceStr + "'");
    }
}

Output:

Original String: '  Hello   World  '
String without white spaces: 'HelloWorld'

Explanation:

  • str.replace(" ", "") replaces all spaces in the string with an empty string.

3. Using Regular Expressions

Regular expressions can be used to remove all types of white space characters (spaces, tabs, newlines) from a string.

Example:

public class RemoveWhiteSpaceUsingRegex {
    public static void main(String[] args) {
        String str = "  Hello \t World \n ";

        // Remove all white spaces using regular expressions
        String noWhiteSpaceStr = str.replaceAll("\\s", "");

        System.out.println("Original String: '" + str + "'");
        System.out.println("String without white spaces: '" + noWhiteSpaceStr + "'");
    }
}

Output:

Original String: '  Hello 	 World
 '
String without white spaces: 'HelloWorld'

Explanation:

  • str.replaceAll("\\s", "") removes all white space characters (including spaces, tabs, and newlines) from the string using the regular expression \\s.

4. Using Apache Commons Lang StringUtils

The Apache Commons Lang library provides a utility class StringUtils that offers a method to remove white spaces from a string. To use this method, you need to add the Apache Commons Lang library to your project.

Maven Dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Example:

import org.apache.commons.lang3.StringUtils;

public class RemoveWhiteSpaceUsingStringUtils {
    public static void main(String[] args) {
        String str = "  Hello   World  ";

        // Remove all white spaces using StringUtils.deleteWhitespace()
        String noWhiteSpaceStr = StringUtils.deleteWhitespace(str);

        System.out.println("Original String: '" + str + "'");
        System.out.println("String without white spaces: '" + noWhiteSpaceStr + "'");
    }
}

Output:

Original String: '  Hello   World  '
String without white spaces: 'HelloWorld'

Explanation:

  • StringUtils.deleteWhitespace(str) removes all white spaces from the string.

5. Complete Example Program

Here is a complete program that demonstrates all the methods discussed above to remove or trim all white spaces from a string in Java.

Example Code:

import org.apache.commons.lang3.StringUtils;

public class RemoveWhiteSpaceExample {
    public static void main(String[] args) {
        String str = "  Hello \t World \n ";

        // Using replaceAll() Method
        String noWhiteSpaceStr1 = str.replaceAll("\\s+", "");
        System.out.println("Using replaceAll():");
        System.out.println("Original String: '" + str + "'");
        System.out.println("String without white spaces: '" + noWhiteSpaceStr1 + "'\n");

        // Using replace() Method
        String noWhiteSpaceStr2 = str.replace(" ", "");
        System.out.println("Using replace():");
        System.out.println("Original String: '" + str + "'");
        System.out.println("String without white spaces: '" + noWhiteSpaceStr2 + "'\n");

        // Using Regular Expressions
        String noWhiteSpaceStr3 = str.replaceAll("\\s", "");
        System.out.println("Using Regular Expressions:");
        System.out.println("Original String: '" + str + "'");
        System.out.println("String without white spaces: '" + noWhiteSpaceStr3 + "'\n");

        // Using StringUtils.deleteWhitespace() Method
        String noWhiteSpaceStr4 = StringUtils.deleteWhitespace(str);
        System.out.println("Using StringUtils.deleteWhitespace():");
        System.out.println("Original String: '" + str + "'");
        System.out.println("String without white spaces: '" + noWhiteSpaceStr4 + "'");
    }
}

Output:

Using replaceAll():
Original String: '  Hello 	 World
 '
String without white spaces: 'HelloWorld'

Using replace():
Original String: '  Hello 	 World
 '
String without white spaces: 'Hello	World
'

Using Regular Expressions:
Original String: '  Hello 	 World
 '
String without white spaces: 'HelloWorld'

Using StringUtils.deleteWhitespace():
Original String: '  Hello 	 World
 '
String without white spaces: 'HelloWorld'

6. Conclusion

Removing or trimming all white spaces from a string in Java can be accomplished in several ways. The replaceAll() method is a powerful and flexible solution, while the replace() method is simpler and useful for specific cases. Regular expressions provide a robust way to handle all types of white space characters. The Apache Commons Lang StringUtils class offers a convenient utility method. By understanding these different methods, you can choose the one that best fits your needs and coding style.

Happy coding!

Comments