Home > OS >  Function to count words
Function to count words

Time:01-18

So I have a task to write a program that counts how many words are in a string. The words can be separated by whitespace or any symbols. The problem I have is that it's not passing one of my autotests.

The autotest input: "Space... The final frontier... These are the voyages of the starship Enterprise. Its five-year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!"

The function for this example returns 32 instead of 38.

I have realized that there is a problem with my counter because it resets to 0. But I don't understand why it's doing that. How do I fix it?

int count_words(const char *str)

{

    int count=0;

    while(*str!='\0')

    {

       if((count!=0 && !isalpha(*str) && isalpha(*(  str))|| (count==0 && isalpha(*str))))

       {

           count  ;

       }

       if(*str=='\0')

       break;

    str  ;

    }

    return count;

}

CodePudding user response:

You need to track whether you are currently "in a word" or not "in a word". When you transition from "not in" to "in", then you can count another word.

int count_words(const char *str)
{
    int count = 0;
    bool inword = false;
    for( ; *str; str   )
    {
        if( isalpha(*str) )
        {
            if( !inword )
                count   ;
            inword = true;
        }
        else
        {
            inword = false;
        }
    }
    return count;
}
  • Related