Java Program to remove leading and trailing whitespace from a string

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Dec-2018 06:55:00
Advertisements