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


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM