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:
- What is strip(), stripLeading() and stripTrailing() methods?
- How to use them?
How to Remove Whitespaces in String in Java 11 using Strip methods?...!!! Click To Tweet
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.
stripLeading() : This method returns a string whose value is this string, with all leading white space removed.
stripTrailing() : This method returns a string whose value is this string, with all trailing white space removed.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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:
1 2 3 | 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?...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts: