Search code examples
javatrim

Does trim() method removes CRLF characters also?


Suddenly noticed that trim() method removes CRLF - new line - characters also..:

String s = "str\r\n";
s = s.trim();

System.out.println("--");
System.out.print(s);
System.out.println("--");

Is it intended to do so?


Solution

  • Yes, see the doc:

    Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).

    CR+LF: CR (U+000D) followed by LF (U+000A) less than U+0020