0
我与这个程序有问题,我希望它只在输入中显示一次单词,并在每次出现时计数,但它显示输入的每个单词。计数相似单词
例如,如果我进入
“这应该也只是出现出现一次”
的话,我想程序输出
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;
}
注意:如果你不太理解,你应该从索引0开始使用数组。 – MikeCAT