How to Remove Leading and Trailing White Space From a String in Java

Introduction

Removing leading and trailing white space from a string is a common task in Java programming. Whether you are processing user input, cleaning data, or manipulating strings, trimming white space is often necessary. Java provides several methods to accomplish this. In this blog post, we will explore different methods to remove leading and trailing white space from a string in Java.

Table of Contents

  1. Using String.trim()
  2. Using String.strip()
  3. Using String.stripLeading() and String.stripTrailing()
  4. Using Regular Expressions
  5. Complete Example Program
  6. Conclusion

1. Using String.trim()

The String.trim() method removes leading and trailing white space from the string. This method does not remove white spaces inside the string.

Example:

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

        // Remove leading and trailing white space using trim()
        String trimmedStr = str.trim();

        System.out.println("Original String: '" + str + "'");
        System.out.println("Trimmed String: '" + trimmedStr + "'");
    }
}

Output:

Original String: '   Hello World!   '
Trimmed String: 'Hello World!'

Explanation:

  • str.trim() removes leading and trailing white space from the string.

2. Using String.strip()

The String.strip() method, introduced in Java 11, removes leading and trailing white space using the Unicode standard. This method is more comprehensive than trim() as it handles all Unicode white space characters.

Example:

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

        // Remove leading and trailing white space using strip()
        String strippedStr = str.strip();

        System.out.println("Original String: '" + str + "'");
        System.out.println("Stripped String: '" + strippedStr + "'");
    }
}

Output:

Original String: '   Hello World!   '
Stripped String: 'Hello World!'

Explanation:

  • str.strip() removes leading and trailing white space from the string using the Unicode standard.

3. Using String.stripLeading() and String.stripTrailing()

The String.stripLeading() and String.stripTrailing() methods, introduced in Java 11, remove only leading or trailing white space, respectively.

Example:

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

        // Remove leading white space using stripLeading()
        String leadingStrippedStr = str.stripLeading();

        // Remove trailing white space using stripTrailing()
        String trailingStrippedStr = str.stripTrailing();

        System.out.println("Original String: '" + str + "'");
        System.out.println("Leading Stripped String: '" + leadingStrippedStr + "'");
        System.out.println("Trailing Stripped String: '" + trailingStrippedStr + "'");
    }
}

Output:

Original String: '   Hello World!   '
Leading Stripped String: 'Hello World!   '
Trailing Stripped String: '   Hello World!'

Explanation:

  • str.stripLeading() removes only the leading white space from the string.
  • str.stripTrailing() removes only the trailing white space from the string.

4. Using Regular Expressions

Regular expressions can be used to remove leading and trailing white space from a string.

Example:

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

        // Remove leading and trailing white space using regular expressions
        String regexTrimmedStr = str.replaceAll("^\\s+|\\s+$", "");

        System.out.println("Original String: '" + str + "'");
        System.out.println("Regex Trimmed String: '" + regexTrimmedStr + "'");
    }
}

Output:

Original String: '   Hello World!   '
Regex Trimmed String: 'Hello World!'

Explanation:

  • str.replaceAll("^\\s+|\\s+$", "") removes leading and trailing white space from the string using regular expressions.

5. Complete Example Program

Here is a complete program that demonstrates all the methods discussed above to remove leading and trailing white space from a string in Java.

Example Code:

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

        // Using String.trim() Method
        String trimmedStr = str.trim();
        System.out.println("Using String.trim():");
        System.out.println("Original String: '" + str + "'");
        System.out.println("Trimmed String: '" + trimmedStr + "'\n");

        // Using String.strip() Method
        String strippedStr = str.strip();
        System.out.println("Using String.strip():");
        System.out.println("Original String: '" + str + "'");
        System.out.println("Stripped String: '" + strippedStr + "'\n");

        // Using String.stripLeading() Method
        String leadingStrippedStr = str.stripLeading();
        System.out.println("Using String.stripLeading():");
        System.out.println("Original String: '" + str + "'");
        System.out.println("Leading Stripped String: '" + leadingStrippedStr + "'\n");

        // Using String.stripTrailing() Method
        String trailingStrippedStr = str.stripTrailing();
        System.out.println("Using String.stripTrailing():");
        System.out.println("Original String: '" + str + "'");
        System.out.println("Trailing Stripped String: '" + trailingStrippedStr + "'\n");

        // Using Regular Expressions
        String regexTrimmedStr = str.replaceAll("^\\s+|\\s+$", "");
        System.out.println("Using Regular Expressions:");
        System.out.println("Original String: '" + str + "'");
        System.out.println("Regex Trimmed String: '" + regexTrimmedStr + "'");
    }
}

Output:

Using String.trim():
Original String: '   Hello World!   '
Trimmed String: 'Hello World!'

Using String.strip():
Original String: '   Hello World!   '
Stripped String: 'Hello World!'

Using String.stripLeading():
Original String: '   Hello World!   '
Leading Stripped String: 'Hello World!   '

Using String.stripTrailing():
Original String: '   Hello World!   '
Trailing Stripped String: '   Hello World!'

Using Regular Expressions:
Original String: '   Hello World!   '
Regex Trimmed String: 'Hello World!'

6. Conclusion

Removing leading and trailing white space from a string in Java can be accomplished in several ways. The String.trim() method is straightforward and widely used. The String.strip(), String.stripLeading(), and String.stripTrailing() methods provide more comprehensive handling of Unicode white space characters and additional control. Regular expressions offer a flexible and powerful way to remove white space. By understanding these different methods, you can choose the one that best fits your needs and coding style.

Happy coding!

Comments