数词出现 [英] Count word occurrence

查看:72
本文介绍了数词出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序逻辑有问题,我希望该程序只显示每个单词一次以及出现的次数。我的逻辑错误是第二次使用strcmp for循环。

I'm having a problem with the logic in my program, I want this program to only display each word once and the number of times they occur. The error in my logic is at the second for loop with the strcmp.

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

At the moment it checks every string individually and if they are not the same it copies it into the string array. However, this logic is not right because unless I enter the same word every time there will always be a string that is different.

例如,如果我输入


你好今天你好吗

hello how are are you today

我想要它仅显示

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

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

Is there any way to fix my logic?

#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;
}


推荐答案

您的内部循环做出了改变每次 迭代 count 。相反,它应该循环直到找到匹配项为止(此时可以增加单词的 count 并停止循环),或者,如果完成循环,则永远不会找到一个匹配项匹配,然后将其添加到令牌 s的列表中。

Your inner loop makes a change to count on every iteration. Instead, it should loop until either it has found a match (at which point it can increment that word's count and stop looping) or, if it finishes the loop never having found a match, only then add it to the list of tokens.

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

Also, if there are any matches, then the number of words in token will be less than the number of words in the string, which means you need different variables to track each of those.

这篇关于数词出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆