【问题标题】:Program counting words c程序计数字 c
【发布时间】:2012-12-29 06:57:54
【问题描述】:

我有一个几乎很好的工作程序来计算标准输入中的单词。 what has to be count 是一个程序参数。

问题是我使用空格来查看单词,但我也必须在单词本身内计数。 示例:如果我的输入是 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;
}

【问题讨论】:

  • 什么?你有两个词:aaaaaa
  • if my input is aa aaaa #EOF, and I want to count aa the result should be 4 为什么你的结果应该是 4?
  • 因为aaaa这个词其实有3次aa,第一个是aa aa,第二个是aaaa,第三个是aaaa.
  • 这是我见过的最奇怪的word概念。
  • 您的代码将除空格之外的任何内容定义为单词字符。我们通常不会将逗号或引号字符视为单词字符。但我认为这对你的问题并不重要。

标签: c counting


【解决方案1】:

你有这个:

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;

【讨论】:

  • 只需阅读上面的 cmets。为了让它在寻找 aa 时为 aaa aaaa 提供 4,仅在匹配时添加 1,而不是添加匹配的全长。我展示的会给你3。
【解决方案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;
}

【讨论】:

  • 谢谢,这实际上非常简单易懂。我实际上是在尝试检查单词的大小。
【解决方案3】:

在循环中尝试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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多