统计相似的单词

标签 c arrays string

我对该程序有疑问,我希望它只在输入中显示一次单词并在每次出现时进行计数,但它会显示输入的每个单词。

例如,如果我输入

"this should only only appear appear once"

然后我想让程序输出

this 1 
should 1 
only 2 
appear 2 
once 1

如有任何帮助,我们将不胜感激。

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

#define ROW 1000
#define COL 50

int read_input(char *str, int n);

int main(void)
{
    char str[ROW];
    char stringSeperate[ROW][COL] = { };
    const char *s= " ,.!";  

    char *p;
    int freq[ROW];
    int i = 0;
    int wordCount = 0;
    int pos = 0;

    read_input(str, ROW);

    p = strtok(str,s);
    i = 1;

    while(p !=NULL) {
        wordCount = i;
        for(i = 0; i < wordCount; i++) {
             if (strcmp(p, stringSeperate[i]) != 0) 
                pos = 1;
            else
                pos = i;
        }
        if (pos == 1) {
            strcpy(stringSeperate[i], p);           
            freq[i++]++;

        }
        else
            freq[pos]++;
        p = strtok(NULL,s);
    }

    for ( i = 1; i <= wordCount; i++ ) {
        printf("Word: %s\t Number: %d\n",stringSeperate[i], freq[i]);
    }

    return 0;
}

int read_input(char *str, int n) 
{
    int ch, i = 0;

    while((ch = getchar()) != '\n') {
        if ( i < n ) {
            *str++ = ch;
            i++;
        }
    }
    *str = '\0';
    return i;
}

最佳答案

您通过使用具有自动存储持续时间(不确定)的未初始化变量 freq 的值来调用未定义的行为

int freq[ROW] = {0};一样初始化它

你也应该

1.将 stringSeperate 的初始化更改为标准:不允许空初始化器,所以它应该像

char stringSeperate[ROW][COL] = {{0}};

2.删除额外的打印以匹配所需的输出:更改

printf("Word: %s\t Number: %d\n",stringSeperate[i], freq[i]);

printf("%s %d\n",stringSeperate[i], freq[i]);

3.检查输入的长度以免导致缓冲区溢出。改变

if ( i < n ) {

read_input中到

if ( i < n - 1 ) {

以便为终止空字符腾出空间。

关于统计相似的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35952555/

相关文章:

javascript - 使用 Set 从数组中删除重复项,保留最高的 id

javascript - JS : need a css color code based on a string

java - 在字符串中使用@符号

c - 如何在 C 中将 char 指针转换为 float?

将长字符数组转换为字节数组

c# - 匹配来自两个列表(或数组)的项目

c# - 如何检查对象是否包含字节数组?

c++ - 将超过 64 位的数组转换为 base-10 字符串

c++ - LuaJIT FFI cdef 不理解 'class' ?

c - 尝试在调试期间进行不需要的附加