A、 B 、 C 是 3 个字符串。把 A 中包含的所有 B 都替换为 C ,如果替换以后还有 B 就继续替换,直到 A 不包含 B 为止。

A、 B 、 C 是 3 个字符串。把 A 中包含的所有 B 都替换为 C ,如果替换以后还有 B 就继续替换,直到 A 不包含 B 为止。
请编写程序实现以上功能。不允许使用系统提供的字符串比较、查找和替换函数

//原生indexOf重写用来查找
String.prototype.myIndexOf = function(str) {
    let sourceArr = this.split('');
    let num = -1;
    for (let i in sourceArr) {
        if (sourceArr[i] === str.slice(0, 1)) {
            if (str === this.slice(i, Number(i) + str.length)) {
                num = i
            }
        }
    }
    return num
}

//原生Map重写用来替换
Array.prototype.myMap = function(fn, context) {
    let arr = this;
    let temp = [];
    for (let j = 0; j < arr.length; j++) {
        let result = fn.call(context, arr[j], j, arr);
        temp.push(result);
    }
    return temp;
}

let a1 = 'aaaBb13cccBb13ffBb13';
let b1 = 'Bb13';
let c1 = 'Cc4';

function find(a, b, c) {
    while (true) { //while a中没有b时结束
        let findnum = a.indexOf(b); //获取a中b的开始下标
        if (findnum != -1) { //通过下标查询
            let Aarr = a.split(''); //切割成数组
            a = '';
            let count = 0;
            Aarr.myMap((item, index) => {
                if (index >= findnum && index < findnum + b.length) {
                    if (count == 0) {
                        a += c;
                    }
                    count++;
                } else {
                    a += Aarr[index];
                }
            })
        } else {
            return a;
        }
    }
}
let f = find(a1, b1, c1);
console.log(f);

函数myIndexOf()仍有问题,望大佬指点

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值