, asked
Views : 3

The correct way to trim a string in Java.

I need to eliminate spaces around a String. Can anyone explain with an example how to do so?

1 Answer
Priya Pallavi

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

Example:

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

Advertisements
Related Questions