1

我有一个几乎很好的工作程序来计算标准输入中的单词。必须计数的词是程序参数。

问题是我使用空格来查看单词,但我也必须在单词本身内计数。示例:如果我的输入是 aa aaaa #EOF,并且我想计算 aa,那么结果应该是 4。我的代码结果是 2。

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


int word_cnt(const char *s, char *argv[])
{
    int cnt = 0;

    while(*s != '\0')
    {
        while(isspace(*s))
        ++s;
        if(*s != '\0')
        {
            if(strncmp(s, argv[1], strlen(argv[1])) == 0)
            ++cnt;

            while(!isspace(*s) && *s != '\0')
            ++s;
        }
     }

    return cnt;
}

int main(int argc, char *argv[])
{
    char buf[1026] = {'\0'};
    char *p="#EOF\n";
    int tellen = 0;

    if (argc != 2)
    {
        printf("Kan het programma niet uitvoeren, er is geen programma argument gevonden\n");
        exit(0);
    }

    while((strcmp(buf, p) !=0))
    {
        fgets (buf, 1025, stdin);
        tellen += word_cnt(buf, argv);
    }

    printf("%d", tellen);

    return 0;
}
4

3 回答 3

3

你有这个:

if(strncmp(s, argv[1], strlen(argv[1])) == 0)
    ++cnt;

while(!isspace(*s) && *s != '\0')
    ++s;

试试这个:

/* if it matches, count and skip over it */
while (strncmp(s, argv[1], strlen(argv[1])) == 0) {
    ++cnt;
    s += strlen(argv[1]);
}

/* if it no longer matches, skip only one character */
++s;
于 2012-12-28T22:22:45.787 回答
2
int word_cnt(const char *s, char *argv[])
{
    int cnt = 0;
    int len = strlen(argv[1]);
    while(*s)
    {
            if(strncmp(s, argv[1], len) == 0)
              ++cnt;

            ++s;
     }

    return cnt;
}
于 2012-12-28T22:49:46.613 回答
1

在循环中尝试strncmp() 。

/* UNTESTED */
unsigned wc(const char *input, const char *word) {
    unsigned count = 0;
    while (*input) {
        if (strncmp(input, word, strlen(word)) == 0) count++;
        input++;
    }
    return count;
}
于 2012-12-28T22:57:54.277 回答