书籍替换字符串中连续出现的制定字符串(5)0805

题目

给定三个字符串str from和to,把str中所有from的子串全部替换成to字符串,对连续出现from的部分要求只替换成一个to字符串,返回最终的结果字符串。

举例

str = “123abc” from=“abc” to=“4567” 返回 1234567

str=“123” from=“abc” to=“456” 返回123

str=“123abcabc” from=“abc” to=“X” 返回123X

public class REPLACE {
    public static void main(String[] args) {
        String str = "123abc";
        String from = "abc";
        String to = "4567";
        System.out.println(new REPLACE().replace(str, from, to));
    }



    public  String replace(String str, String from, String to) {
        if (str == null || from == null || to == null || str.equals("") || from.equals("")) {
            return str;
        }
        char[] chas = str.toCharArray();
        char[] chaf = from.toCharArray();
        int match = 0;
        for (int i = 0; i < chas.length; i++) {
            if (chas[i] == chaf[match++]) {
                if (match == chaf.length) {
                    clear(chas, i , chaf.length);
                    match = 0;
                }

            }else { // 出现不匹配的字符,重置match
                match = 0;
            }
        }
        String res ="" ;
        String cur ="";
        for (int i = 0; i < chas.length; i++) {
            if (chas[i] != 0) {
                cur += chas[i];
            }
            if (chas[i] == 0 && (i == 0 || chas[i-1] != 0)){
                res = res + cur + to;
                cur = "";
            }
        }
        if (!cur.equals("")){
            res = res + cur;
        }
        return res;
    }
    public  void clear ( char[] chas, int end, int len){
        while (len-- != 0) {
            chas[end--] = 0;
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值