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

Java实现:仅用charAt方法统计句子中单词出现次数(禁用其他API)

解决仅用charAt统计指定单词每行出现次数的问题

嘿,我明白你现在卡在全字符匹配这一步了——只靠首字母判断肯定没法精准统计,咱们一步步来搞定这个需求,而且严格只用charAt API,保证符合要求!

核心思路拆解

要匹配完整的目标单词(比如"dog"),关键是找到首字符后,逐字符验证后续的所有字符是否完全匹配,同时要避免数组越界的问题。具体步骤如下:

  • 先获取目标单词的长度,确定每次需要检查的字符数量;
  • 遍历每行文本的每个可能起始位置(注意不能超过行长度减去单词长度,否则会越界);
  • 当找到首字符匹配时,逐个检查后续字符是否和目标单词对应位置一致;
  • 若全部匹配,计数器加1;
  • 遍历完每行后输出结果。

代码实现(基础版:连续字符匹配)

下面用JavaScript实现这个逻辑,完全只使用charAt API:

function countWordOccurrences(targetWord, lines) {
  const wordLength = targetWord.length;
  // 遍历每一行文本
  lines.forEach((line, lineIndex) => {
    let occurrenceCount = 0;
    const lineLength = line.length;
    // 遍历到行长度-单词长度的位置,避免越界
    for (let i = 0; i <= lineLength - wordLength; i++) {
      // 先检查首字符是否匹配
      if (line.charAt(i) === targetWord.charAt(0)) {
        let isFullMatch = true;
        // 逐个检查后续字符
        for (let j = 1; j < wordLength; j++) {
          if (line.charAt(i + j) !== targetWord.charAt(j)) {
            isFullMatch = false;
            break; // 只要有一个字符不匹配,直接跳出循环
          }
        }
        if (isFullMatch) {
          occurrenceCount++;
        }
      }
    }
    console.log(`第${lineIndex + 1}行出现${occurrenceCount}次`);
  });
}

// 测试你的输入示例
const target = "dog";
const inputLines = [
  "dog My dog is very cute dog",
  "Every dog passes by another dog",
  "dogs will bark at another dog",
  "They are very cute"
];
countWordOccurrences(target, inputLines);

运行这段代码后,输出会是:

第1行出现3次
第2行出现2次
第3行出现2次
第4行出现0次

适配独立单词的需求(可选)

如果你的需求是统计作为独立单词的"dog"(比如不包含"dogs"里的"dog"),那我们需要在匹配成功后额外检查单词的边界(前后是空格、标点或者行首/行尾)。修改后的代码如下:

function countWordOccurrences(targetWord, lines) {
  const wordLength = targetWord.length;
  lines.forEach((line, lineIndex) => {
    let occurrenceCount = 0;
    const lineLength = line.length;
    for (let i = 0; i <= lineLength - wordLength; i++) {
      if (line.charAt(i) === targetWord.charAt(0)) {
        let isFullMatch = true;
        for (let j = 1; j < wordLength; j++) {
          if (line.charAt(i + j) !== targetWord.charAt(j)) {
            isFullMatch = false;
            break;
          }
        }
        if (isFullMatch) {
          // 检查单词边界:前后是空格/标点,或者是行首/行尾
          const isStartOfLine = i === 0;
          const isEndOfLine = i + wordLength === lineLength;
          const prevIsValid = isStartOfLine || 
            line.charAt(i - 1) === ' ' || 
            line.charAt(i - 1) === '.' || 
            line.charAt(i - 1) === ',';
          const nextIsValid = isEndOfLine || 
            line.charAt(i + wordLength) === ' ' || 
            line.charAt(i + wordLength) === '.' || 
            line.charAt(i + wordLength) === ',';
          
          if (prevIsValid && nextIsValid) {
            occurrenceCount++;
          }
        }
      }
    }
    console.log(`第${lineIndex + 1}行出现${occurrenceCount}次`);
  });
}

运行这个版本,你的输入示例输出会是:

第1行出现3次
第2行出现2次
第3行出现1次
第4行出现0次

(注:你的示例里预期第三行是4次,可能是输入内容有误或者需求描述偏差,可以根据实际情况调整边界判断的规则~)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:09:23