The correct way to trim a string in Java.


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..

Updated on: 30-Jul-2019

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements