改bug过程中的新发现,重新认识String trim方法

来源:互联网 发布:mac上qq截图快捷键 编辑:程序博客网 时间:2024/05/14 23:35



今天遇到一个奇葩的问题,一个字符串包含了"\n"换行符,再执行trim()方法后,“\n”被去掉。

 于是研究了下trim()的源码,源码如下:


[html] view plain copy
  1. public String trim() {  
  2.    int len = count;  
  3.    int st = 0;  
  4.    int off = offset;      /* avoid getfield opcode */  
  5.    char[] val = value;    /* avoid getfield opcode */  
  6.   
  7.    while ((st < len) && (val[off + st] <= ' ')) {  
  8.        st++;  
  9.    }  
  10.    while ((st < len) && (val[off + len - 1] <= ' ')) {  
  11.        len--;  
  12.    }  
  13.    return ((st > 0) || (len < count)) ? substring(st, len) : this;  
  14.    }  

从源码可以看出,是从字符数组的第一个位置开始往后查找,直到找到字符的asicii码大于‘ ’的索引,再从字符数组的最后一个位置开始往前查找,

直到找到字符的asicii码大于‘ ’的索引,最后通过substring方法截取2个索引之间的部分作为返回值,

[html] view plain copy
  1. char s = '\n';  
  2. int index = s;  
  3. System.out.println(index);  
  4. s = ' ';  
  5. index = s;  
  6. System.out.println(index);  
通过以上代码,打印出‘\n’和' '的asicii码得到结果为10 32,‘\n’的asicii码为10,小于空字符' '的32,所以在截取字符串的时候,‘\n’不会被截取。
原创粉丝点击