c - 使用子串来计算单词出现的次数

标签 c

我想使用子字符串来计算输入特定单词的次数。我一直在研究我的代码,看看是否可以让它工作,但我就是不明白!

我的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main(int argc, char *argv[])
{

int i=0;

char buf[1026]={'\0'};
char *p="#EOF\n";
char *t;

while (strcmp(buf, p) != 0)
{
    fgets(buf, 1025, stdin);
    t=strtok(buf," , - \n");
    while(t != NULL)
    {
        if(strncmp(t, argv[1], strlen(argv[1])) == 0)
    {
        i++;
    }
    }
}






printf("%d\n", i);

return 0;
}

没有错误,但是i的值总是0。我不知道如何确保它在找到单词一次后继续计数。我试过 sizeof(t) < j ,但这不起作用。

最佳答案

如果您要查找 token 的多个实例,则需要多次调用 strtok。在后续调用中,将 NULL 作为第一个参数传递。查看man page

此外,sizeof(t) 是一个常量,可能是 4 或 8。t 是一个字符指针,它占用一些字节。如果您要查看 strtok 是否返回了您想要与 NULL 进行比较的内容。从手册页:

RETURN VALUE

  The strtok() and strtok_r() functions return a pointer 
   to the next token, or  NULL  if there are no more tokens.

NULL 是您要检查的内容,以确定该行上没有更多标记。

另请注意,如果 token 桥接两个读取,您将无法获得它。例如第 1 行以“,”结尾,下一个 ready 以“-\n”开始

关于c - 使用子串来计算单词出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824871/

相关文章:

c - 如何为 postgresql 创建一个返回两个或多个 OUT 参数的 C 语言函数?

c - 如何在 C 中使用枚举类型结构?

c - 代码的执行顺序

c - 了解 C 中的栈帧

c - 如何在 Objective-C/ANSI C 中创建用于对象实例化的宏

Android NDK 内存使用

c - 从 fgets 获取第一个单词

c指针引用和取消引用

c - 出现错误 : Stack around the variable was corrupted

允许确定哪个 PID 正在使用它们的跨平台同步原语