Java Program to remove leading and trailing whitespace from a string


Use the Trim() method to remove leading and trailing whitespace from a string. Let’s say the following is our string with white spaces in the beginning and the end.

String str = " a ";

Now, use the trim() method.

str.trim()

The following is the final example with output.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = " a ";
      System.out.println("Text = "+str);
      System.out.println("Text after using trim() method = " + str.trim());
    }
}

Output

Text = a
Text after using trim() method = a

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

359 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements