Java.lang.String.trim() Method


Advertisements


Description

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

Declaration

Following is the declaration for java.lang.String.trim() method

public String trim()

Parameters

  • NA

Return Value

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.

Exception

  • NA

Example

The following example shows the usage of java.lang.String.trim() method.

package com.tutorialspoint;

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() + "..");
   }
}

Let us compile and run the above program, this will produce the following result:

Before trim = .. This is TutorialsPoint ..
After trim = ..This is TutorialsPoint..

java_lang_string.htm

Advertisements