You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现循环起始位置逐次后移的非等长字符串匹配

解决方案:滑动窗口遍历子串匹配

你的需求本质是用滑动窗口的方式,在ocrString中逐个截取与pattern长度相同的子串,逐一对比是否匹配。原代码的逻辑是逐个字符交叉对比,不符合你要的"从起始位置后移一位遍历整个字符串找匹配"的需求,下面是修正后的实现:

let ocrString = "casaidespcasa";
let pattern = "idesp";
let matchCount = 0;

checkIDESP(ocrString, pattern);

function checkIDESP(ocrString, pattern) {
    const patternLength = pattern.length;
    const ocrLength = ocrString.length;

    // 遍历所有可能的起始位置,确保子串长度等于pattern
    for (let i = 0; i <= ocrLength - patternLength; i++) {
        // 截取从i开始、长度为patternLength的子串
        const currentSubstring = ocrString.substring(i, i + patternLength);
        console.log(`当前遍历子串: ${currentSubstring}`);

        // 对比子串与pattern是否完全匹配
        if (currentSubstring === pattern) {
            matchCount++;
        }
    }

    if (matchCount === 0) {
        console.log(`未找到匹配,匹配次数: ${matchCount}`);
    } else {
        console.log(`找到${matchCount}次匹配,符合目标特征`);
    }
}

关键逻辑说明:

  • 计算pattern的长度,确定每次截取子串的固定长度
  • 循环起始索引i的终止条件设为ocrLength - patternLength,避免截取子串时超出原字符串范围
  • 用substring(i, i + patternLength)直接获取当前窗口的子串,无需拆分数组,更简洁高效
  • 直接对比子串与pattern是否完全相等,精准匹配连续字符序列

如果需要支持部分字符匹配(比如允许少量差异),可以在截取子串后再逐个字符对比统计匹配度,但从你的需求描述来看,上述代码已经满足核心的连续子串匹配要求。

内容的提问来源于stack exchange,提问作者b28

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:00:52