replace和replaceAll的一点发现

         今天ui设计师小妹,在矫正ui。突然对我说,嘿,你这条数据怎么间距这么大。我一看不对呀,就是一个Recyclerview,然后每个Item理论上是一致的呀。怎么就这条数据跟别人不一样呢?然后,我就看了看数据,果然服务器返回数据中带了一个特殊的符号,那就是\r\n.哎呀,妈呀,换行符号。怪不得我的那个Item跟下面间距多了一行。

          好的,问题定位了,就是服务器返回多了一个换行符号。本想说这个是服务器返回数据的问题。可是ui小妹不妥协,必须要改,影响ui美观。那咱就改吧,毕竟我们都是认真的人,哈哈哈。然后我就想将这种符号直接替换成空字符串""就好了嘛。然后我就写了stringA.replace("\\r\\n","");运行了一遍可是效果没出来,依然间距很大。很是纳闷。那就试试,replaceAll吧,然后就好使了。那就比较疑惑了,为什么一个好使,另外一个就不行呢?那就得看看两者的区别了。

          replace(CharSequence target, CharSequence replacement)方法,sdk中解释如下:

/**
     * Returns a copy of this string after replacing occurrences of {@code target} replaced
     * with {@code replacement}. The string is processed from the beginning to the
     * end.
     *
     * @throws NullPointerException
     *             if {@code target} or {@code replacement} is {@code null}.
     */
       大意就是这个方法将会返回一个将target出现的地方都会被替换为replacement的复本。这种替换是从开始到结束的。当然如果被替换字符或者替换字符的传入为null,是会抛出空指针异常的啦。

        然后我们看看replaceAll(String regularExpression, String replacement)在sdk中的解释:

 /**
     * Replaces all matches for {@code regularExpression} within this string with the given
     * {@code replacement}.
     * See {@link Pattern} for regular expression syntax.
     *
     * <p>If the same regular expression is to be used for multiple operations, it may be more
     * efficient to reuse a compiled {@code Pattern}.
     *
     * @throws PatternSyntaxException
     *             if the syntax of the supplied regular expression is not
     *             valid.
     * @throws NullPointerException if {@code regularExpression == null}
     * @see Pattern
     * @since 1.4
     */

         一看,还真的是有所发现,你看第一个被替换的参数是regularExpression正则表达式呀,然后我又突然想到了,我用replace方法时候我是将替换后的字符串打印了出来的,当时是有看到我要替换的\r\n是没有了即被替换为了“”。但是它带来的格式还在,就是换行效果是还在的。然后又看到replaceAll方法的解释,就明白了,因为\r\n是转义字符,所以单纯的替换字符串是不行的。所以要用replaceAll方法,是以正则表达式来替换的,是有格式的校验的。        

       以上如有不对之处,欢迎批评指正。



         

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值