java trim()方法哪位高手给解释一下这段代码

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

while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}

public String trim() {
int len = count; // 有效字符(不是空格)结束位置
int st = 0; // 有效字符(不是空格)起始位置
int off = offset; // 字符数组起始位置,应该是0
char[] val = value; // 字符数组

while ((st < len) && (val[off + st] <= ' ')) { // 从起始位置开始遍历,获取起始连续空格的最后空格位置
st++; // st值发生变化,说明起始有空格,st就是起始需要截取的位置
}
while ((st < len) && (val[off + len - 1] <= ' ')) { // 从末尾位置开始遍历,获取末尾连续空格的第一个空格位置
len--; // len值发生变化,说明末尾有空格,len是末尾需要截取的位置
}
return ((st > 0) || (len < count)) ? substring(st, len) : this; // 判断是否有空格需要截取,有截取,没有返回原String
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-04
纯属自己语言,看不懂可以私聊
public String trim() {
int len = count; //你可以理解为这个字符串变成char数组以后的长度
int st = 0;
int off = offset; /* avoid getfield opcode */ //当做是0
char[] val = value; /* avoid getfield opcode */ //由这个字符串变成的字符数组
while ((st < len) && (val[off + st] <= ' ')) { //var[off+st]其实是拿到这个数组的首字符,由首字符和‘ ’的ascii码比较,如果<=就继续下一个字符比较,如果>了就停止比较;最后st会拿到第一个不是 ‘ ‘字符的下标
st++;
}
//下面这个逻辑和上面一样,其实拿到就是一个最后一个字符不是’ ‘的下标。
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
//最后返回的是截取这个字符串中下标从st开始到len结束的一个字符串。
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
第2个回答  2014-11-04
消除字符串的俩端空白内容!
第3个回答  2014-11-04
就是去除空格的方法
相似回答