【java刷题杂记】String与StringBuffer的replace方法区别

String的replace方法

  1. 直接翻看文档:
public String replace(CharSequence target,
                      CharSequence replacement)
Replaces each substring of this string that 
matches the literal target sequence with
 the specified literal replacement sequence. 
The replacement proceeds from the 
beginning of the string to the end, 
for example, replacing "aa" with "b" 
in the string "aaa" will result in "ba" rather than "ab".
  1. 这里面重点便是Replaces each substring-----说明可以替换字符串中所有的目标字符串(这是与StringBuffer中的replace很大不同),而且不必在意长度不对称问题
  2. 注意返回值:调用该方法后返回新字符串-----因为String在分配空间之后,大小就不会改变了,在替换之后必须要通过创建一个新的String类对象,并返回

StringBuffer的replace方法

  1. 直接翻看文档:
    方法原型:public StringBuffer replace(int start, int end, String str)
    方法描述:
    Replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start. (This sequence will be lengthened to accommodate the specified String if necessary.)
  2. 可以发现,不用关心长度不对称问题,字符串长度会自动调整
  3. 注意,也是通过返回来获取新字符串
  4. 但是该方法只能替换一处位置-----通过下标指定
  5. 而String的replace方法通过目标子字符串来指定

总结对比

  1. String方法可替换多处位置,且通过目标字符串来查询,返回String类
  2. StringBuffer方法只能替换一处位置,且通过下标来查询—而下标可通过indexOf()方法来找出。返回StringBuffer类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值