Print the longest word in a line

I wrote the following code

#include<stdio.h>

int main(void)
{
    int i, max = 0, count = 0, j;
    char str[] = "I'm a programmer";

    for(i = 0; i < str[i]; i++)
    {
        if (str[i] != ' ')
            count++;
        else
        {
            if (max < count)
            {
                j = i - count;
                max = count;
            }
            count = 0;
        }
    }
    for(i = j; i < j + max; i++)
        printf("%c", str[i]);

    return 0;
}

      

With the intention of finding and printing the longest word, but does not work when the longest word is the last time as I am a programmer . I typed I instead of a programmer

How to solve this problem, someone gives me a hand

+3


source to share


2 answers


The end condition of your loop for

is wrong. It should be:

    for(i = 0; i < strlen(str) + 1; i++)

      

and also, since at the end of the line you have not' '

, but you have '\0'

, you must change:



    if (str[i] != ' ')

      

in

    if (str[i] != ' ' && str[i] != '\0')

      

+2


source


The problem should be pretty obvious. You update your longest word found when the character you are viewing is space. But there is no space after the long word in the test line, so the code update for it is never done.

You can just flip that code after the loop and that should do the trick.



Note, however, that you could trivially find this by adding only printfs showing the progress of this function.

0


source







All Articles