Remove leading and trailing spaces from a string in Java

In this tutorial, we are learning how to remove leading and trailing spaces from a string in Java. We can remove leading and trailing spaces from a string using these methods:

  • trim()
  • strip()

Using the trim function to remove leading and trailing spaces in Java

It is defined in the String class of java.lang package. When we invoke the trim() function, it doesn’t replace the string but returns a new string. To access it we need to assign it to a new string variable.trim() is used to remove ASCII characters less than or equal to ’32’ (according to unicode (‘U+0020’)).

String a1=" This is a String ";
String a2 ="\u2000 This is a String \u2001";
String b1=a1.trim(); 
String b2=a2.trim();
System.out.println("'"+a1+"'"); 
System.out.println("'"+a2+"'"); 
System.out.println("'"+b1+"'");
System.out.println("'"+b2+"'");

Here I have initialized a string that consists of leading and trailing spaces. Then trim() function is used on that string and it is reassigned to a new string variable and the output looks like as below:

' This is a String '
'? This is a String ?'
'This is a String'
'? This is a String ?'

Using the strip function

strip() function is added in Java 11 to remove leading and trailing spaces in a string. when we invoke the strip() function, it doesn’t replace the string but returns a new string. To access it we need to assign it to a new string variable.strip() function is used to remove all spaces according to the Unicode.

String a1=" This is a String ";
String a2 ="\u2000 This is a String \u2001";
String b1=a1.strip(); 
String b2=a2.strip();
System.out.println("'"+a1+"'"); 
System.out.println("'"+a2+"'"); 
System.out.println("'"+b1+"'");
System.out.println("'"+b2+"'");

Here I have initialized a string that consists of leading and trailing spaces. Then strip() function is used on that string and it is reassigned to a new string. So the output looks like as below:

' This is a String '
'? This is a String ?'
'This is a String'
'This is a String'

There are other methods for removing leading and trailing space.

  • stripLeading()
  • stripTrailing()

By using stripLeading() we can only remove leading spaces from a string.

String a ="    This  is  a  String    ";
System.out.println("'"+a+"'");
String c=a.stripLeading();
System.out.println("'"+c+"'");

The output looks like this:

'   This is a String   '
'This is a String   '

By using stripTrailing() we can only remove trailing spaces from a string.

String a ="    This  is  a  String    ";
System.out.println("'"+a+"'");
String c=a.stripTrailing();
System.out.println("'"+c+"'");

The output looks like this:

'   This is a String   '
'   This is a String'

Also read: How to remove leading zeros from a string in Java

Leave a Reply

Your email address will not be published. Required fields are marked *