Thread: cstring algorithm.. what do you think?

  1. #1
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    cstring algorithm.. what do you think?

    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
    Last edited by The Brain; 01-24-2005 at 07:35 AM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  2. #2
    Registered User Sake's Avatar
    Join Date
    Jan 2005
    Posts
    89
    >>which may unecessarily complicate the algorithm
    Just a hair. Without strcmp and strcpy it would be as easy as:
    Code:
    #include <cstring>
    #include <iostream>
    
    using namespace std;
    
    size_t longest_word(char array[])
    {
      size_t max = 0;
    
      for (char *t = strtok(array, " \t\n");
        t != 0; t = strtok(0, " \t\n"))
      {
        size_t len = strlen(t);
    
        if (len > max)
          max = len;
      }
    
      return max;
    }
    
    int main()
    {
      char array[] = "Some kind of wonderful";
    
      cout<<"The longest word was "
          << longest_word(array) <<" characters"<<endl;
    }

  3. #3
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    Talking <cstring> exercise

    Here is my finished program. Please test it out and let me know how it works Hopefully others learning c++ can learn something from my program.. if you have any questions, please ask


    The Breakdown:

    The longest_word( ) algorithm works like this:

    1. Initialize Everything
    2. Make a copy of the user input
    3. Tokenize the user input (and it's copy) and keep an array of pointers that point to the first letter of each word in the user's input
    4. Now that I can readily identify and access each individual word - Compare each word length against every other word (using nested 'for' loops)
    5. Return the character count of the longest word




    *will only work on compilers that support the non-standard <conio.h> library I like clrscr( ) and getch( ), what can i say

    Code:
    #include<iostream>    //Provides cin, cout, & NULL
    #include<cstring>    //Provides strcpy(), strtok(), & strlen()
    #include<conio.h>    //Provides clrscr() & getch()
    using namespace std;
    
    //Function Prototypes
    int longest_word(char*);
    
    
    int main( )
    {
        char user_input[81];
    
        do{
    
            //Input array initialization
            for(int c=0; c<80; c++)
            
                user_input[c]=NULL;
            
            
            clrscr();
    
            cout << "\n\tEnter a sentence: ";
            cin.getline(user_input, 80);
    
            cout << "\n\n\tThe longest word contains  " << longest_word(user_input)
                 << " characters. ";
    
            cout << "\n\n\tWould you like to try again? (Y/N) ";    
    
        }while(toupper(getch())=='Y');
    
        clrscr();
    
        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 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
        int longest_word= 0;  //will contain the character count of the longest word
    
        //Array Initializations
        for(int c=0; c<80; c++)
    
            temp[c]=NULL;
    
        for(int c=0; c<20; c++)
        {
            words1[c]=NULL;
            words2[c]=NULL;
        }
    
        
        //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 this 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-1); p++)
        {
            //The inner loop will continuously cycle through words1[] pointer array comparing
            //each word to that of words2[] (user_input array)
            for(int q=0; q<(word_count-1); q++)
            {
                //if word1 is greater than word2
                if(strlen(words1[q]) > strlen(words2[p]))
    
                    word_length = strlen(words1[q]);
    
                //if word1 is less than or equal to word2
                else 
    
                    word_length = strlen(words2[p]);
            
    
            }//end INNER for
    
        if(word_length>longest_word)
    
            longest_word = word_length;
    
        }//end OUTTER for
    
    return longest_word;
    
    }//end FUNCTION
    Last edited by The Brain; 01-25-2005 at 01:36 PM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  4. #4
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Suggestions == good
    I'd just do something like this:
    Code:
    int longest_word(char* s)
    {
      int longest = 0, l=0;
      s--;
      do {   
        s++;
        if (*s==' ' || *s==0) { 
          if (l>longest)
            longest = l;
          l=0;
        }
        else
            l++; 
      } while (*s != 0);
      return longest;      
    }
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  5. #5
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    you guys make it look so easy..!
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Sang-drax
    I'd just do something like this:
    Code:
    int longest_word(char* s)
    {
      int longest = 0, l=0;
      s--;
      do {   
        s++;
        if (*s==' ' || *s==0) { 
          if (l>longest)
            longest = l;
          l=0;
        }
        else
            l++; 
      } while (*s != 0);
      return longest;      
    }
    I wouldn't. You shouldn't be walking off the low end of a string, just like you wouldn't walk off the high end. You're just asking for a segfault here. Sure, you just increment it in a bit anyway, but you still shouldn't be walking off the end of a string.
    Code:
    int longestword( char * s )
    {
        int longest = 0, word = 0;
        char *ptr = s;
        while( *ptr )
        {
            if( isspace( *ptr ) )
            {
                if( word > longest )
                    longest = word;
                word = 0;
            }
            else
                word++;
            ptr++;
        }
        return longest;
    }
    I suppose you should really check to make sure you aren't passing it NULL...

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,130
    I suppose you should really check to make sure you aren't passing it NULL...
    And for some extra icing on the cake, make it const correct
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. Help with CString class and operator+ overloading
    By skanxalot in forum C++ Programming
    Replies: 2
    Last Post: 10-07-2003, 10:23 AM