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

使用strcmp()比较字符串字符与字符常量失效问题求助

问题:用strcmp比较单个字符统计句子数量失败

我希望根据句子结尾的!、?或.字符统计任意文本中的句子数量,但使用strcmp()函数比较文本中的单个字符与对应字符常量时,未能得到预期的0值(匹配结果)。调试输出后仍无法理解问题原因,恳请帮助。

以下是我的代码:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int count_sentences(string text);

int main(void)
{
    string text = get_string("text: ");
    //printf("%s\n", text);
    count_sentences(text);
    //printf("%i\n", strcmp("!", "!"));
}

int count_sentences(string text)
{
    int string_length = strlen(text);
    int num_of_sentences = 0;
    const char sent_ind1 = '?';
    const char sent_ind2 = '!';
    const char sent_ind3 = '.';
    //printf("%c %c %c", sent_ind1, sent_ind2,
    //sent_ind3);
    for (int i = 0; i < string_length; i++)
    {
        int value1 = strcmp(&text[i], &sent_ind1);
        int value2 = strcmp(&text[i], &sent_ind2);
        int value3 = strcmp(&text[i], &sent_ind3);
        if (value1 == 0 || value2 == 0 || value3 == 0)
        {
            num_of_sentences += 1;
        }
        //printf("1- %i 2- %i 3- %i i- %c c- %c si0 %c si1 %c si2 %c\n",
        //value1, value2, value3, i, text[i], sent_ind1, sent_ind2,
        //sent_ind3);
        //printf("1- %i 2- %i 3- %i i- %i\n",
        //sent_ind1, sent_ind2, sent_ind3, text[i]);
    }
    //printf("string length equal %i and number of sentences equal %i.\n",
    //string_length, num_of_sentences);
    return num_of_sentences;
}

问题原因与解决方法

  1. 错误核心:strcmp()的作用是比较两个以'\0'结尾的完整字符串,而非单个字符。你传入的&text[i]是从第i位开始到文本末尾的子串,而&sent_ind1指向的单个字符后没有字符串结束符'\0',strcmp()会越界读取内存,导致结果完全不可控。

  2. 直接修复方案:既然是判断单个字符是否匹配,直接用字符相等运算符==即可,完全不需要调用strcmp()。修改后的循环代码如下:

for (int i = 0; i < string_length; i++)
{
    if (text[i] == sent_ind1 || text[i] == sent_ind2 || text[i] == sent_ind3)
    {
        num_of_sentences += 1;
    }
}
  1. 代码优化:可以用strchr()函数简化判断逻辑,该函数会检查字符是否存在于指定的字符串中,代码更简洁:
for (int i = 0; i < string_length; i++)
{
    if (strchr("?!.", text[i]) != NULL)
    {
        num_of_sentences += 1;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:57:37