今天遇到一个奇葩的问题,一个字符串包含了"\n"换行符,再执行trim()方法后,“\n”被去掉。
于是研究了下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;
- }
从源码可以看出,是从字符数组的第一个位置开始往后查找,直到找到字符的asicii码大于‘ ’的索引,再从字符数组的最后一个位置开始往前查找,
直到找到字符的asicii码大于‘ ’的索引,最后通过substring方法截取2个索引之间的部分作为返回值,
- char s = '\n';
- int index = s;
- System.out.println(index);
- s = ' ';
- index = s;
- System.out.println(index);
通过以上代码,打印出‘\n’和' '的asicii码得到结果为10 32,‘\n’的asicii码为10,小于空字符' '的32,所以在截取字符串的时候,‘\n’不会被截取。