java中string.trim()函数的作用
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()的实际作用是去掉字符串首尾的空格。
附: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;
}