计数单词出现

时间:2016-03-12 16:48:30

标签: c arrays string

我的程序中存在逻辑问题,我希望这个程序只显示每个单词一次以及它们出现的次数。我的逻辑中的错误是在strcmp的第二个for循环中。

此刻它会单独检查每个字符串,如果它们不相同,则会将其复制到字符串数组中。但是,这种逻辑是不对的,因为除非每次输入相同的单词,否则总会有一个不同的字符串。

例如,如果我输入

  

你好,今天你好吗

我希望它只显示

word: hello times: 1
word: how   times: 1
word: are   times: 2
word: you   times: 1
word: today times: 1

我的程序将显示

word: hello times: 1
word: how   times: 1
word: are   times: 2
word: are   times: 1
word: you   times: 1
word: today times: 1

有没有办法解决我的逻辑?

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

#define ROW 200
#define COL 20

int read_input(char *str, int n);

int main(void)
{
    char input[ROW];
    char tokens[ROW][COL+1] = {{0}};
    const char *s= " ,";    
    char *pch;
    int count[ROW] = {0};
    int i, j = 0;
    int wordCount = 0;

    // read input from user
    read_input(input, ROW);

    // break input into tokens
    pch = strtok(input,s);

   while (pch != NULL) {
        wordCount = i;

        for(j = 0; j < i; j++) {

            // compare tokens with array
            if (strcmp(pch, tokens[j]) != 0) {
                strcpy(tokens[i], pch);         
                count[i++] = 1;
            }
            // if tokens are the same increment word
            else
                count[j]++;
        }
        pch = strtok(NULL,s);

    }

    for ( i =1 ; i <= wordCount; i++ ) {
        printf("COL #: %d Word: %s\t Times: %d\n",i, tokens[i], count[i]);
    }

    return 0;
}

2 个答案:

答案 0 :(得分:0)

您需要使用If。其中字符串是映射中的“唯一”键,而int将是其计数器。

答案 1 :(得分:0)

您的内部循环会在每次迭代时对count进行更改。相反,它应该循环,直到它找到一个匹配(此时它可以增加该单词&#39; s count并停止循环),或者,如果它完成循环从未找到匹配,则仅添加它列在token s。

列表中

此外,如果有任何匹配,则token中的单词数量将少于字符串中单词的数量,这意味着您需要使用不同的变量来跟踪每个单词。

相关问题