#include #include #include #include #include #define MAX_WORDS 2000 /* max number of words */ #define MAX_WORD_LENGTH 30 /* max length of a word */ typedef char Word_t[MAX_WORD_LENGTH + 1]; typedef struct { Word_t word; int count; } ListEntry_t; ListEntry_t entries[MAX_WORDS]; /* a table of words/counts */ int wordCount = 0; /* current number of words */ Word_t currentWord ; /* word being processed */ int InWordList() { int i; for (i = 0; i < wordCount; ++i) { if (strcmp(entries[i].word, currentWord) == 0) { return i; /* found */ } } return -1; /* not found */ } void IncrementCount (int i) { entries[i].count += 1; } void AddToList() { if (wordCount == MAX_WORDS) { printf("Word list is full!\n"); return; } if (strlen (currentWord) >= MAX_WORD_LENGTH) { printf("Word too long!\n"); return; } strcpy(entries[wordCount].word, currentWord); /* backwards! */ entries[wordCount].count = 1; wordCount++; } void WriteList() { int i; printf("%d words found\n", wordCount); printf("***************************\n"); for (i = 0; i < wordCount; ++i) { printf("%3d %s\n", entries[i].count, entries[i].word); } } char SkipWhiteSpace() { int ch ; do {ch = getchar() ;} while (ch != EOF && isspace(ch)) ; return ch ; } int ReadWord() { int i=0, c=SkipWhiteSpace() ; if (c==EOF) return 0 ; while (c != EOF && !isspace(c) && i < MAX_WORD_LENGTH) { currentWord[i] = c; ++i; c = getchar(); } if (i==MAX_WORD_LENGTH) return 0 ; currentWord[i] = '\0' ; return 1 ; } int main(void) { int index; while (ReadWord()) { index = InWordList(); if (index != -1) IncrementCount(index); else AddToList(); } WriteList(); }