Java Program to remove whitespace from the beginning and end of a string


Use the trim() method to remove whitespace from the beginning and end of a string.

Let’s say the following is our string with whitespace.

str1 = " The Big Bang Theory ";

Now, let us trim all the whitespaces from the beginning and the end.

String str2 = str1.trim();

The following is the final example with output.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str1 = " The Big Bang Theory ";
      System.out.println("String: "+str1);
      String str2 = str1.trim();
      System.out.println("Updated string (trimming spaces): "+str2);
   }
}

Output

String: The Big Bang Theory
Updated string (trimming spaces): The Big Bang Theory

Updated on: 25-Jun-2020

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements