OneBite.Dev - Coding blog in a bite size

trim a string in java

Code snippet on how to trim a string in java

  String stringToTrim = "  Hello World  ";
  stringToTrim = stringToTrim.trim();

  System.out.println("Original string: "+stringToTrim);
  System.out.println("Trimmed string: "+stringToTrim);

This code sample shows how to trim a string in Java. The first line declares a string named stringToTrim and assigns it the value ” Hello World “. Then the string is trimmed by calling the trim method on the stringToTrim. Afterwards the original and trimmed strings are printed to the console with two System.out.println commands. The output would look like this: “Original string: Hello World Trimmed string: Hello World”. The trim method has removed the white spaces from the beginning and end of the string.

java