strip() method in String class

In Java 11 a new method strip() has been introduced in String class. It is used to remove all the trailing and leading white space characters from the string.

strip() method returns the string after removing these white spaces. If the string only consists of white spaces then an empty string is returned.

Let us look at an example :-

public class StripExample {

	public static void main(String[] args) {
		
		// string with spaces at start and end
		String str1 = "    This is Tech4Humans   ";
		System.out.println("str1 = "+str1.strip());         // str1.strip() returns "This is Tech4Humans"
		
		
		// string with new line and tab white space characters 
		String str2 = "\n\t   This is Tech4Humans   ";
		System.out.println("str2 = "+str2.strip());       // str2.strip() returns "This is Tech4Humans"
		
		
		// string only containing spaces
		String str3 = "       ";
		System.out.println("str3 = "+str3.strip());       // str3.strip() returns empty string
		
		
		// string only containing white space characters
		String str4 = "    \n \t  ";
		System.out.println("str4 = "+str4.strip());      // str4.strip() returns empty string
	}

}

Output

str1 = This is Tech4Humans
str2 = This is Tech4Humans
str3 = 
str4 = 

Let us look at now another method of Java 11 – stripLeading method.

Leave a Comment