Java String strip Example

1. Introduction

This blog post discusses the strip() method in Java's String class. Introduced in Java 11, strip() is a method that removes leading and trailing white space from a string, using the Unicode definition of white space.

Definition

String.strip() is a method that removes any leading and trailing white space based on the Unicode definition of what constitutes a white space character. It is Unicode-aware, making it more versatile than trim() for certain use cases involving different character sets.

2. Program Steps

1. Create strings with leading and trailing white spaces, including Unicode white space characters.

2. Use the strip() method to remove these white spaces.

3. Display the results after stripping the white spaces.

3. Code Program

public class StringStripExample {
    public static void main(String[] args) {
        String example1 = "   Hello, Java!   ";
        String example2 = "\u2005\u2005Java and Unicode\u2005";

        // Using strip() to remove white spaces
        String stripped1 = example1.strip();
        String stripped2 = example2.strip();

        // Displaying the results
        System.out.println("Original: '" + example1 + "'");
        System.out.println("Stripped: '" + stripped1 + "'");
        System.out.println("Original: '" + example2 + "'");
        System.out.println("Stripped: '" + stripped2 + "'");
    }
}

Output:

Original: '   Hello, Java!   '
Stripped: 'Hello, Java!'
Original: '  Java and Unicode '
Stripped: 'Java and Unicode'

Explanation:

1. example1 and example2 are strings with leading and trailing white spaces. example2 includes Unicode white space characters (\u2005).

2. String.strip() is used on these strings to remove the white spaces.

3. The output shows the original and stripped versions of each string.

4. For example1, typical spaces are removed. In example2, strip() successfully removes the Unicode white spaces, demonstrating its effectiveness over traditional trim() in handling various white space characters.

5. This example illustrates the utility of String.strip() in Java for removing leading and trailing white spaces, especially in contexts involving Unicode characters.


Comments