/* * The function fsm_words() takes a string (text file) as an input * and it prints out parsed word. * * This is a demonstration of a concept that students can use for other * purposes. * * CSCI 363 demonstration * Spring 2014 * Xiannong Meng */ #include #include #include /* for u_int32_t etc. */ #include /* for isspace() etc. */ #include #define WS 0 /* white space */ #define WORD 1 /* word */ #define NUM 2 /* number */ u_int16_t STATES[] = {WS, WORD}; int wordCount = 0; /* count of words */ /* * Assume text is a string of words separated by white spaces. * A word is defined as sequence of letters or digits. E.g., * 'hello', '12how', '125' are all words. Anything * other than letters or digits will be considered as a delimiter. */ void word_fsm(char * text) { u_int16_t state = WS; char ch; int index = 0; int i = 0; int len = strlen(text); char * currentWord = (char*)malloc(len); while (index < len) { ch = text[index]; switch (state) { case WS: if (!isspace(ch)) { if (isalnum(ch)) { state = WORD; wordCount ++; currentWord[i] = ch; i ++; } } /* if (!isspace(ch)) */ break; case WORD: if (!isalnum(ch)) { currentWord[i] = 0; /* terminate the string */ i = 0; /* reset the index within a word */ printf("%s\n", currentWord); state = WS; } else { /* if (isspace(ch)) */ currentWord[i] = ch; i ++; } } /* switch */ index ++; } /* while */ } /* word_fsm() */ int main(int argc, char* argv[]) { /* usage: prog < input-text */ int MAXLEN = 1024; /* some arbitrary length */ char text[MAXLEN + 1]; int i = 0; while (i < MAXLEN && scanf("%c",&(text[i]))) { i ++; } text[i] = 0; /* terminate the string */ word_fsm(text); /* process the text */ return 0; }