stripLeading() method in String class

stripLeading() method has been introduced in String class of Java 11. It is used to remove all the leading white space characters from the string and return the remaining string. It means it removes white spaces that comes at beginning of the string.

If the string only contains the white spaces then an empty string is returned.

Let us look at an example code

public class StripLeadingExample {

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

}

Output

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

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

Leave a Comment