1. 程式人生 > >java中string.trim()函數的作用

java中string.trim()函數的作用

main ati cnblogs return style ret blog substr system

trim /[tr?m] / 英文意思:整理,修理,修剪,整齊的

trim()的作用:去掉字符串首尾的空格。

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));  
    }

執行結果:
a: hello world ,false
a:hello world,true

trim()的源代碼:

public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */

        while ((st < len) && (val[st] <= ‘ ‘)) {
            st++;
        }
        while
((st < len) && (val[len - 1] <= ‘ ‘)) { len--; } return ((st > 0) || (len < value.length)) ? substring(st, len) : this; }

java中string.trim()函數的作用