实现移除字符串最长单词功能:需手动重写push、filter、replace方法
移除字符串中最长单词的函数实现(手动重写核心方法)
需求说明
- 实现一个输入为字符串的函数,移除字符串中所有最长的单词(单词定义:以空格分隔的字符组,包含字符串首尾与空格相邻的字符组)
- 禁止使用原生的
.push()、.filter()和.replace()方法,需手动实现对应功能 - 当前现有代码存在问题:
arrPush方法未返回修改后的数组,导致无法正确收集所有单词 - 预期输出结果:
word wooord wooooooord. woooooord woooord
修改后的完整代码
function deleteTheLongestWord(str){ let arrSent = strSplit(str, "."); let allWords = []; let biggestWord = ''; // 收集所有单词 for (const elem in arrSent) { let words = strSplit(arrSent[elem], ' '); for (const word in words) { allWords = arrPush(allWords, words[word]); } } // 找出最长单词 for (const i in allWords) { if(biggestWord.length < allWords[i].length){ biggestWord = allWords[i]; } } // 过滤出所有最长单词 allWords = arrFilter(allWords, function(e){ return e.length === biggestWord.length; }); // 移除所有最长单词 for (let i = 0; i < allWords.length; i++) { str = strReplace(str, " " + allWords[i], ''); // 处理开头的最长单词(无前置空格的情况) if(str.startsWith(allWords[i] + " ")){ str = strReplace(str, allWords[i] + " ", ''); } else if(str === allWords[i]){ str = ''; } } console.log(str); } // 手动实现push功能:添加元素到数组末尾并返回数组 function arrPush(arr, item){ arr[arr.length] = item; return arr; // 修复:返回修改后的数组 } // 手动实现filter功能:遍历数组,保留符合条件的元素 function arrFilter(arr, callback){ const result = []; for(let i = 0; i < arr.length; i++){ if(callback(arr[i], i, arr)){ arrPush(result, arr[i]); // 使用自己实现的arrPush } } return result; } // 手动实现replace功能:替换字符串中所有指定子串 function strReplace(str, searchValue, replaceValue){ let result = ''; let startIndex = 0; const searchLen = searchValue.length; while(startIndex < str.length){ const foundIndex = str.indexOf(searchValue, startIndex); if(foundIndex === -1){ // 剩余部分直接拼接 result += str.slice(startIndex); break; } // 拼接找到的子串之前的部分 result += str.slice(startIndex, foundIndex); // 拼接替换值 result += replaceValue; // 更新起始位置 startIndex = foundIndex + searchLen; } return result; } // 修复后的strSplit方法 function strSplit(str, delimiter){ const arr = [""]; const len = delimiter.length; let idx = 0; for (let i = 0; i < str.length; i++) { let sample = ""; for (let x = i; x < i + len; x++) { sample += str[x]; } if (sample === delimiter) { i += len - 1; // 修复原逻辑:避免跳过后续字符 idx += 1; arr[idx] = ""; } else { arr[idx] += str[i]; } } return arr; } // 测试调用 deleteTheLongestWord('word wooord wooooooooord wooooooord. wooooooooord woooooord woooord wooooooooord');
关键修改说明
修复
arrPush方法:- 原方法未返回修改后的数组,导致
allWords = arrPush(...)赋值后变为undefined - 修改后添加
return arr;,确保数组能正确接收新元素
- 原方法未返回修改后的数组,导致
实现
arrFilter方法:- 遍历输入数组,对每个元素执行传入的回调函数
- 将回调返回
true的元素收集到新数组中,使用自己实现的arrPush添加元素
实现
strReplace方法:- 循环查找目标子串的位置,逐个替换为指定值
- 处理了所有出现的子串,而非仅第一个
- 在主函数中额外处理了开头的最长单词(无前置空格的情况),确保所有最长单词都被移除
修复
strSplit的小问题:- 原逻辑中遇到分隔符后
i += len会跳过后续一个字符,修改为i += len - 1,避免字符丢失
- 原逻辑中遇到分隔符后
内容的提问来源于stack exchange,提问作者user526218
相关产品推荐
相关产品推荐

