Java - String String Trimming

Introduction

trim() method removes all leading and trailing whitespaces and control characters from a string.

trim() method removes characters from the string, which have Unicode value less than \u0020 (decimal 32).

For example,

  • " hello ".trim() will return "hello"
  • "hello ".trim() will return "hello"
  • "\n \t\t\t\t \r \t hello\n\n\n\r\r" will return "hello"

trim() method removes only leading and trailing whitespaces.

It does not remove any whitespace or control characters in the middle.

For example,

" he\nllo   ".trim() will return  "he\nllo" because \n is inside the string.
"h ello".trim() will return  "h ello" because the space is inside the string.

Demo

public class Main {
  public static void main(String[] args) {
    System.out.println("   hello  ");
    System.out.println("hello    ");
    System.out.println("\n \t\t\t\t  \r \t  hello\n\n\n\r\r");
    System.out.println(" he\nllo   ");
    System.out.println("h ello");
    //from w w  w.ja v a  2 s  . com
  }
}

Result

Exercise