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



今天遇到一个奇葩的问题,一个字符串包含了"\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’不会被截取。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值