I want to come up with an algorithm that will return the length of the longest word in a character array. I want to use <cstring> library functions.. specifically the strcpy( ), strtok( ), strlen( ), and strcmp( ) functions (which may unecessarily complicate the algorithm, but this is just for fun) This is what I am thinking about using. What do you guys think?
Suggestions == good
Code:#include<iostream> #include<cstring> using namespace std; //Function Prototypes int longest_word(char*); /* int main( ) { .... .... .... .... return 0; } */ /////FUNCTION DEFINITIONS////// int longest_word(char* user_input) { char temp[81]; //create a temporary array char* words1[20]; //create an array of pointers (pointers to tokenized words) char* words2[20]; //create an array of pointers to words int compare = 0; //this will hold strcmp( ) results int word_length = 0; //this hold the number of characters in the longest word int word_count = 0; //will hold number of words in user inputted char array //Make a copy of user_input[] strcpy(temp, user_input); //Begin array tokenization routines //create an array of pointers to words // //These tokenization routines are based //on the web tutorial http://www.cplusplus.com/ref/cstring/strtok.html //Tokenize temp array word_count=1; words1[0] = strtok(temp, " "); while(words1[(word_count-1)]!=NULL) //examine the previously entered element, and terminate the loop { //if previous element == NULL words1[word_count] = strtok(NULL, " ,."); //this might look kinda complex, but strtok( ) is basically word_count++; //just returning pointers to each word from the temp[] array. }; //Tokenize user_input array word_count=1; words2[0] = strtok(user_input, " "); while(words2[(word_count-1)]!=NULL) { words2[word_count] = strtok(NULL, " ,."); //populate words2[] with pointers to the words in user_input[] word_count++; }; //The purpose of this next block of code, is to compare each //word against every other word // //The outter loop will be used to step through the words2[] word pointer array //Each iteration of the outter loop will increment to the next word //of words2 (user_input) using the 'p' loop counter. for(int p=0; p<word_count; p++) //The inner loop will continuously cycle through words1[] pointer array comparing //each word to that of words2[] (user_input array) for(int q; q<word_count; q++) { compare = strcmp(words1[q], words2[p]); //if word1 is greater than word2 if(compare>0) word_length = strlen(words1[q]); //if word1 is less than or equal to word2 else word_length = strlen(words2[p]); }//end INNER for //}end OUTTER for return word_length; }//end FUNCTION



LinkBack URL
About LinkBacks
) This is what I am thinking about using. What do you guys think? 



Without strcmp and strcpy it would be as easy as: