如何不使用indexOf等内置函数查找子串索引?现有代码仅支持单字符
优化字符串子串索引查找的实现
你的现有代码仅通过单个字符比对,无法处理长度大于1的子串匹配。下面提供两种实用的优化方案,同时兼容单个字符和多字符子串的查找需求:
方案一:循环截取子串比对
核心思路是根据目标子串的长度,每次从原字符串的当前位置截取等长的子串进行匹配,同时处理边界避免越界。如果需要支持重叠子串匹配(比如在'aaaa'中查找'aa',返回[0,1,2]),每次循环索引递增1;如果不需要重叠匹配,索引直接递增目标子串的长度即可。
优化后的代码:
const findAllIndices = (stringToCheck, target) => { const indices = []; const targetLength = target.length; // 处理目标为空串的边界情况 if (targetLength === 0) return indices; // 循环终止条件:当前索引位置加上目标长度不超过原字符串长度 for (let i = 0; i <= stringToCheck.length - targetLength; i++) { // 截取当前位置开始的等长子串与目标比对 if (stringToCheck.slice(i, i + targetLength) === target) { indices.push(i); // 若不需要重叠匹配,可替换为 i += targetLength - 1; } } console.log(indices); return indices; }; // 测试示例 findAllIndices('the dog jumps over the river', 'the'); // 输出 [0, 18] findAllIndices('the dog jumps over the river', 'o'); // 输出 [5, 14] findAllIndices('aaaa', 'aa'); // 输出 [0, 1, 2](重叠匹配)
方案二:正则表达式全局匹配
利用正则的全局匹配特性,通过exec循环获取所有匹配结果的起始索引。需要注意的是,若目标子串包含正则特殊字符(如.、*、+等),要先对其进行转义,避免匹配逻辑出错。
优化后的代码:
const findAllIndices = (stringToCheck, target) => { const indices = []; if (target.length === 0) return indices; // 转义正则特殊字符 const escapedTarget = target.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // 创建全局匹配的正则表达式 const regex = new RegExp(escapedTarget, 'g'); let match; // 循环获取所有匹配结果 while ((match = regex.exec(stringToCheck)) !== null) { indices.push(match.index); // 若需要支持重叠匹配,需手动调整lastIndex regex.lastIndex = match.index + 1; } console.log(indices); return indices; }; // 测试示例 findAllIndices('the dog jumps over the river', 'the'); // 输出 [0, 18] findAllIndices('the dog jumps over the river', 'o'); // 输出 [5, 14] findAllIndices('aaaa', 'aa'); // 输出 [0, 1, 2](重叠匹配) findAllIndices('a.b.c', '.'); // 输出 [1, 3](转义特殊字符后正确匹配)
内容的提问来源于stack exchange,提问作者user2824374
相关产品推荐
相关产品推荐

