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

如何统计字符串中特定字符集出现次数?及JS代码计数异常排查

问题解答

问题1:统计字符串中特定字符集合的出现次数

分两种场景给出解决方案:

场景1:统计集合内所有字符的总出现次数

比如统计字符串中a、b、c三种字符的总数量:

  • 正则表达式法:
    const str = "abcabc123xyz";
    const charSet = new Set(['a', 'b', 'c']);
    // 转义正则特殊字符,生成匹配模式
    const safeChars = Array.from(charSet).map(c => /[.*+?^${}()|[\]\\]/.test(c) ? `\\${c}` : c).join('');
    const matchResult = str.match(new RegExp(`[${safeChars}]`, 'g')) || [];
    const totalCount = matchResult.length;
    console.log(totalCount); // 输出6
    
  • 遍历判断法:
    const str = "abcabc123xyz";
    const charSet = new Set(['a', 'b', 'c']);
    let totalCount = 0;
    for (const char of str) {
      if (charSet.has(char)) totalCount++;
    }
    console.log(totalCount); // 输出6
    

场景2:统计字符集合作为连续子串的出现次数

比如统计字符串中if子串的出现次数:

const str = "ififabcif";
const targetSub = "if";
let subCount = 0;
let index = str.indexOf(targetSub);
while (index !== -1) {
  subCount++;
  // 不允许重叠匹配(如"ifif"算2次),若需重叠则改为index + 1
  index = str.indexOf(targetSub, index + targetSub.length);
}
console.log(subCount); // 输出3

问题2:JavaScript代码异常修复

原代码核心问题

  1. keydown事件触发时文本框内容尚未更新,导致判断逻辑基于旧值
  2. 仅单次检查某个位置的if,未遍历整个文本统计总数,无法正确累计字节减少量
  3. bytenum直接全局累加减少,未基于当前文本中if的实际数量计算,重复触发时会重复减扣

修复后的代码

JavaScript部分

const jsInput = document.getElementById('js');
const nesOutput = document.getElementById('nes');
const BASE_SPACE = 40976; // 初始剩余字节数

// 统计文本中"if"的出现次数
function countIfInstances(str) {
  let count = 0;
  let index = str.indexOf('if');
  while (index !== -1) {
    count++;
    index = str.indexOf('if', index + 2); // 跳过已匹配的字符,避免重叠
  }
  return count;
}

// 更新剩余空间显示
function updateFreeSpace() {
  const ifCount = countIfInstances(jsInput.value);
  const remainingSpace = BASE_SPACE - ifCount * 3;
  nesOutput.value = remainingSpace.toString();
}

// 使用keyup事件确保文本已更新后再计算
jsInput.addEventListener('keyup', updateFreeSpace);

// 初始化显示
updateFreeSpace();

HTML部分(保持原结构)

<div id="input">
  <h1>Input (.JS Format)</h1>
  <textarea id="js"></textarea>
</div>
<div id="output">
  <h1>Free Cartridge Space</h1>
  <textarea id="nes"></textarea>
</div>

修复说明

  • 每次文本变化时重新统计所有if的数量,基于初始空间计算剩余值,保证数值准确
  • 改用keyup事件,确保获取到最新的文本内容后再处理
  • 分离统计逻辑和更新逻辑,代码结构更清晰,避免变量污染和重复计算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:37:25