In this post, we will learn “How to remove whitespaces in a string in Java 11?”. Java 11 introduced three new methods strip(), stripLeading() and stripTrailing() to do that.

Here, we are going to learn following things:

  1. What is strip(), stripLeading() and stripTrailing() methods?
  2. How to use them?

How to Remove Whitespaces in String in Java 11 using Strip methods?...!!! Share on X

Let’s Begin,

1. What are strip methods?

Java 11 came up with these 3 methods as part of String class. 

strip() : This method returns a string whose value is this string, with all leading and trailing white space removed.

strip_Java11_Signature_Techndeck

stripLeading() : This method returns a string whose value is this string, with all leading white space removed.

stripLeading_Java11_Signature_Techndeck

stripTrailing() : This method returns a string whose value is this string, with all trailing white space removed.

stripTrailing_Java11_Signature_Techndeck

2. How to use it?

Let’s take an example where we have a word ‘Techndeck’ with leading and trailing whitespaces. And, we are going to use strip methods to remove them.

public class Strip_String_Java11 {

    public static void main(String[] args) {

        String s = "          Techndeck          ";

        //Remove all whitespaces
        System.out.println("String with all whitespaces removed: " + s.strip()); //"Techndeck"

        //Remove all leading whitespaces
        System.out.println("String with all leading whitespaces removed: " + s.stripLeading()); //"Techndeck          "

        //Remove all trailing whitespaces
        System.out.println("String with all trailing whitespaces removed: " + s.stripTrailing()); //"          Techndeck"

    }
}

Output:

String with all whitespaces removed: Techndeck
String with all leading whitespaces removed: Techndeck          
String with all trailing whitespaces removed:           Techndeck

How to Remove Whitespaces in String in Java 11 using Strip methods?...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts