java中的trim()

trim():去掉字符串首尾的空格。但该方法并不仅仅是去除空格,它能够去除从编码’\u0000′ 至 ‘\u0020′ 的所有字符。

回车换行也在这20个字符

例1:

public static void main(String arg[]){  
  
        String a=" hello world ";  
  
        String b="hello world";  
  
        System.out.println(b.equals(a));  
  
        a=a.trim();//去掉字符串首尾的空格  
  
        System.out.println(a.equals(b));  
    }  

例子2:

public class StringTest {
  public static void main(String[] args) {
  char[] chars = {'a','b','c','\r','\n'};
  System.out.println(chars.length);
  String str = new String(chars);
  System.out.println(str.length());
  String newStr = str.trim();
  System.out.println(newStr.length());
 }
}

输出如下:


5
5
3

从输出可以看出,trimI()方法吧\r\n两个字符也去掉了。

 

posted @ 2016-10-10 10:40  虫儿ls  Views(1282)  Comments(0Edit  收藏  举报