Learnitweb

String strip() method in Java

1. Introduction

The syntax of this method is:

String	strip()

This method returns the string after removing returning all its leading and trailing white spaces.

This method was added in Java 11.

A character is a Java whitespace character if and only if it satisfies one of the following criteria:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’).
  • It is ‘\t’, U+0009 HORIZONTAL TABULATION.
  • It is ‘\n’, U+000A LINE FEED.
  • It is ‘\u000B’, U+000B VERTICAL TABULATION.
  • It is ‘\f’, U+000C FORM FEED.
  • It is ‘\r’, U+000D CARRIAGE RETURN.
  • It is ‘\u001C’, U+001C FILE SEPARATOR.
  • It is ‘\u001D’, U+001D GROUP SEPARATOR.
  • It is ‘\u001E’, U+001E RECORD SEPARATOR.
  • It is ‘\u001F’, U+001F UNIT SEPARATOR.

If the String object represents an empty string, or if all code points in this string are white space, then an empty string is returned.

This method may be used to remove all leading and trailing white spaces.

This functioning of this method is in contrast to trim() method, which considers anything less than or equal to U+0020 (space character) as whitespace.

2. Other variations of strip() method

There are two other variations of strip() method.

  • String stripLeading() – This method returns the string after removing all leading white spaces.
  • String stripTrailing() – This method return the string after removing all trailing white spaces.

3. Example

Let us see an example of strip() method.

public class StripMethodExample {
    public static void main(String args[]) {
        String str = " \t  \u2005Java\u2005   \n";
        String strippedString = str.strip();
        System.out.println("Original String: [" + str + "]");
        System.out.println("Stripped String: [" + strippedString + "]");
        System.out.println("Stripped leading white spaces:" + str.stripLeading());
        System.out.println("Stripped trailing white spaces:" + str.stripTrailing());
    }
}

Output

Original String: [ 	   Java    
]
Stripped String: [Java]
Stripped leading white spaces:Java    

Stripped trailing white spaces: 	   Java

4. Conclusion

In conclusion, the strip() method in Java is a powerful addition to the String class, introduced in Java 11. This method simplifies the process of removing leading and trailing whitespace from strings, enhancing readability and ease of manipulation. By using strip(), you can efficiently clean up your strings without the need for complex regex patterns or custom trimming functions.