2018-10-28

Java String strip() method Example

String strip() method


String strip() method added in jdk 11.

String strip() 

Returns a string whose value is this string, with all leading and trailing white space removed.
If this String object represents an empty string, or if all code points in this string are white space, then an empty string is returned.

Otherwise, returns a substring of this string beginning with the first code point that is not a white space up to and including the last code point that is not a white space.

This method may be used to strip white space from the beginning and end of a string.

strip method remove the extra space from both side.

Java Program Example:

class StripMethodExample{
public static void main(String args[]){
//with var variable
var test = "     hello!   ";
System.out.println(test.strip());

//with String class
String test1 = "     hello!   ";
System.out.println(test1.strip());
}
}

Output:

hello!
hello!


1 comment:

  1. Difference between String trim() and strip() methods in Java 11
    Problem with trim
    The current JavaDoc for String::trim does not make it clear which definition of "space" is being used in the code. With additional trimming methods coming in the near future that use a different definition of space, clarification is imperative.

    String::trim uses the definition of space as any codepoint that is less than or equal to the space character codepoint (\u0020.)

    Newer trimming methods will use the definition of (white) space as any codepoint that returns true when passed to the Character::isWhitespace predicate.

    strip() is "Unicode-aware" evolution of trim()
    Character c = '\u2000';
    String s = c + "abc" + c;
    s.strip()

    ReplyDelete