Sunday, January 26, 2014

How to remove leading and trailing whitespace in a string.

Source:
public class RemoveTest {
   public static void main(String[] args) {
      String s1 = "    This is a string     ";

      System.out.println(s1);
      System.out.println("length: " + s1.length());

      //  trim() returns a copy of the string, with leading 
      //  and trailing whitespace omitted.
      String s2 = s1.trim();

      System.out.println(s2);
      System.out.println("length: " + s2.length());

   }
}

Output:
   $ java RemoveTest 
       This is a string     
   length: 25
   This is a string
   length: 16

Blog Archive