The correct way to trim a string in Java.

Java 8Object Oriented ProgrammingProgramming

The trim() method of the java.lang.String class returns a copy of the string omitting the leading and trailing whitespace.

Example

 Live Demo

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      // string with leading and trailing white space
      String str = " This is TutorialsPoint ";
      System.out.print("Before trim = ");
      System.out.println(".." + str + "..");
     
      // leading and trailing white space removed
      System.out.print("After trim = ");
      System.out.println(".." + str.trim() + "..");
   }
}

Output

Before trim = .. This is TutorialsPoint ..
After trim = ..This is TutorialsPoint..
raja
Published on 12-Feb-2018 07:18:18
Advertisements