Trim a string in Java to remove leading and trailing spaces


To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

Let’s say the following is our string with leading and trailing spaces −

String str = new String(" Jack Sparrow ");

Now, let us trim the string −

str.trim()

Following is an example to remove the leading and trailing spaces in Java −

Example

import java.io.*;
public class Main {
   public static void main(String args[]) {
      String str = new String(" Jack Sparrow ");
      System.out.println("String: "+str);
      System.out.print("Result after removing leading and trailing spaces:" );
      System.out.println(str.trim() );
   }
}

Output

String: Jack Sparrow
Result after removing leading and trailing spaces:Jack Sparrow

Updated on: 22-Oct-2023

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements