Connect with us!
How to use String.strip or strip() function in Java?
Overview
strip() is a method or function of String in Java which returns back a string with all leading and trailing white spaces removed. This method was introduced in Java 11.
Example
Let’s declare a String variable str1 with leading and trailing white spaces and another variable str2 without any leading and trailing white spaces.
String str1 = " Apple ";
String str2 = "Apple";
Code
Let’s declare the complete Java code and run it. To setup and run Java in Visual Studio Code checkout this article How to run JAVA using Visual Studio Code – Salow Studios
public class Main {
public static void main(String[] args) {
String str1 = " Apple ";
String str2 = "Apple";
str1 = str1.strip();
str2 = str2.strip();
System.out.println(str1);
System.out.println(str2);
}
}
Output
We can see that both the strings are same without any leading or trailing spaces.
Apple Apple