Java 11 - strip(), stripLeading() and stripTrailing() example

Java 11 added a few useful APIs to the commonly used String class.  In this post, we will see the usage of below String methods with an example.
  • String java.lang.String.strip() - The strip() instance method returns a string with all leading and trailing whitespaces removed.
  • String java.lang.String.stripLeading() - This method returns a string with all leading white space removed.
  • String java.lang.String.stripTrailing() - This method returns a string with all trailing white space removed.
Check out New String APIs/Methods in Java 11 (JDK11) with Examples

String strip(), stripLeading() and stripTrailing() methods - Java 11

  • String java.lang.String.strip() - The strip() instance method returns a string with all leading and trailing whitespaces removed.
  • String java.lang.String.stripLeading() - This method returns a string with all leading white space removed.
  • String java.lang.String.stripTrailing() - This method returns a string with all trailing white space removed.
package net.javaguides.examples;

/**
 * Java 11 (JDK11) New String APIs/Methods with Examples
 * @author Ramesh Fadatare
 *
 */
public class StringAPIInJDK11 {
    public static void main(String[] args) {

        String input1 = "\n\t  hello   \u2005";

        /**
         *  The strip() instance method returns a string
         *  with all leading and trailing whitespaces removed 
         */
        String output1 = input1.strip();
        System.out.println(output1);

        // stripLeading() usage
        System.out.println(input1.stripLeading());

        // stripTrailing() usage
        System.out.println(input1.stripTrailing());
    }
}
Output:
hello
hello   ?

   hello

Reference


Comments