Java String strip()

In this guide, you will learn about the String strip() method in Java programming and how to use it with an example.

1. String strip() Method Overview


The strip() method in Java is part of the String class and was introduced in Java 11. It is used to remove the leading and trailing white spaces from a string. Unlike trim(), which considers anything less than or equal to U+0020 (space character) as whitespace, strip() uses the Unicode Character Property “White_Space” to identify whitespaces.


public String strip()


The method does not take any parameters.

Key Points:

- It removes all kinds of leading and trailing whitespaces as defined by the Unicode standard, not just the space character.

- If the string has no leading or trailing whitespaces, the same string is returned.

- It is Unicode-aware, making it more versatile than trim() for strings that may contain non-ASCII characters.

2. String strip() Method Example

public class StripExample {
    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 + "]");


Original String: [ 	  Java 
Stripped String: [Java]


In this example, the str string contains various types of whitespaces including tabs, spaces, and the Unicode character \u2005 (Four-Per-Em Space) around the word "Java". 

After calling the strip() method, all the leading and trailing whitespaces are removed, and only the word "Java" is left, which is printed to the console.