Trim a string in Java to remove leading and trailing spaces

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 23-Sep-2019 12:24:30
Advertisements