String strip() – Remove leading and trailing white spaces

Learn to use String class’s strip(), stripLeading() and stripTrailing() methods to remove unwanted white spaces from a given string in Java 11.

1. String strip() APIs

Since Java 11, String class includes 3 more methods which help in removing extra white-spaces. These methods use Character.isWhitespace(char) method to determine a white space character.

  • String strip() – returns a string whose value is given string, with all leading and trailing white space removed. Please note that String.trim() method also produces the same result.
  • String stripLeading() – returns a string whose value is given string, with all leading white space removed.
  • String stripTrailing() – returns a string whose value is given string, with all trailing white space removed.
public class Main 
{
	public static void main(String[] args) 
	{
		String str = "  Hello World !!   ";

		System.out.println( str.strip() );			//"Hello World !!"

		System.out.println( str.stripLeading() );	//"Hello World !!   "

		System.out.println( str.stripTrailing() );	//"  Hello World !!"
	}
}

2. Use regex to trim white spaces (including tabs)

In you are not using Java 11 then you can use regular expressions to trim the white spaces around a string.

Regular expressionDescription
^[ \t]+|[ \t]+$Remove leading and trailing white spaces
^[ \t]+Remove only leading white spaces
[ \t]+$Remove only trailing white spaces
public class Main 
{
	public static void main(String[] args) 
	{
		String str = "  Hello World !!   ";

		System.out.println( str.replaceAll("^[ \t]+|[ \t]+$", "") );	//"Hello World !!"

		System.out.println( str.replaceAll("^[ \t]+", "") );			//"Hello World !!   "

		System.out.println( str.replaceAll("[ \t]+$", "") );			//"  Hello World !!"
	}
}

Drop me your questions related to how to remove white spaces and tabs from a string in Java.

Happy Learning !!

Reference:

regular-expressions.info
Java String.strip() API Doc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.