/* * SpellCheck * EE w312 Project 1 submission by * Joseph Ryan * JBR2558 * Slip days used: 0 * Spring 2018 */ #include #include #include #include #define MAX_DICT_SIZE 50000 /* * Converts a string to all lowercase in place and returns a pointer to it. Any * non-uppercase characters are unmodified. */ char* lowerCase(char* str) { size_t len = strlen(str); for(size_t i = 0; i < len; ++i) { if(str[i] >= 'A' && str[i] <= 'Z') { str[i] += 'a' - 'A'; } } return str; } /* * Parses the next "word" per the specifications of the article. On a first call * the function takes the string to be read, and in subsequent calls it expects * NULL. The function will automatically null terminate returned words (this * process is destructive so use a copy of the string if it's needed elsewhere). * When the end of the string is reached, returns NULL. */ char* getNextWord(char* str) { static char* s; if(str != NULL) { s = str; } // Find first alphabetic character to start a word. size_t i = 0; while(!isalpha(s[i])) { if(s[i] == '\0') { return NULL; } ++i; } s = &s[i]; char* startOfWord = s; char* endOfWord = s + 1; // If word is only one letter, skip it. if(!isalpha(*endOfWord)) { ++s; return getNextWord(NULL); } // Find next non-alphabetic character to end the word. while(isalpha(*endOfWord)) { ++endOfWord; } // Only advance the pointer to next word if not already at end of string. s = endOfWord + (*endOfWord != '\0'); *endOfWord = '\0'; return startOfWord; } /* * Destructively converts the given string of newline terminated words to an array * of null terminated strings. Returns the resulting array (must be freed). */ char** parseDict(char* raw) { char delim[] = "\n"; char** dict = (char**)malloc(MAX_DICT_SIZE * sizeof(char*)); char* entry; size_t i = 0; entry = strtok(raw, delim); while(entry != NULL) { dict[i] = lowerCase(entry); ++i; entry = strtok(NULL, delim); } dict[i] = NULL; return dict; } /* * Returns true if the given word is in the given dictionary, otherwise false. */ int inDict(char* word, char** dict) { size_t i = 0; while(dict[i] != NULL) { if(!strcmp(word, dict[i])) { return 1; } ++i; } return 0; } /* * Displays the members of a dictionary for debugging purposes. */ void printDict(char** d) { for(size_t i = 0; d[i] != NULL; ++i) { printf("%s\n", d[i]); } } /* * Displays the contents of an article for debugging purposes. */ void printArticle(char* a) { char* temp = strdup(a); // Make copy since getNextWord() is destructive. char* word = getNextWord(temp); if(word == NULL) { return; } do { printf("%s\n", word); } while(word = getNextWord(NULL)); } /* * Prints each word in the given article that is not found in the given dictionary. */ void spellCheck(char* article, char* dictionary) { char** dict = parseDict(dictionary); char* word = getNextWord(article); if(word == NULL) { return; } do { if(!inDict(lowerCase(word), dict)) { printf("%s\n", word); } } while(word = getNextWord(NULL)); }