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