Hi. I need help finding the longest word in a string. How to return last longest word if there are two or more words with the same (longest) length? My code:

#include <stdio.h>
#include <string.h>
int main()
{
    char string[100], word[20], max[20], min[20], c;
    int i = 0, j = 0, flag = 0;
    printf("Enter string: ");
    gets(string);
    for (i = 0; i < strlen(string); i++)
    {
        while (i < strlen(string) && string[i]!=32 && string[i]!=0)
        {
            word[j++] = string[i++];
        }
        if (j != 0)
        {
            word[j] = '\0';
            if (!flag)
            {
                flag = !flag;
                strcpy(max, word);
            }
            if (strlen(word) > strlen(max))
            {
                strcpy(max, word);
            }
            j = 0;
        }
    }
    printf("The largest word is '%s' .\n", max);
    return 0;
}

You only update the longest word when it's longer than the current word. If you want the last instance of the longest word when there are multiple instances having the same length, update the longest word when it's equal to or longer:

if (strlen(word) >= strlen(max))
{
    strcpy(max, word);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.