Dremendo Tag Line

Input a sentence and print the longest word in C

String Methods - Question 8

In this question, we will see how to to input a sentence and print the longest word in C programming. To know more about string methods click on the string methods lesson.

Q8) Write a program in C to input a sentence and print the longest word.

Program

#include <stdio.h>
#include <conio.h>
#include <string.h>

int main()
{
    char s[100],w[50],lw[50];
    int i,p;

    printf("Enter a sentence\n");
    gets(s);

    for(i=0; i<strlen(s); i++)
    {
        if(s[i]!=' ')
        {
            // store the characters in array w until we find a space
            w[p]=s[i];
            p++;
        }
        else
        {
            // terminate the word by a null character
            w[p]='\0';

            // check if word length is greater than longest word (lw)
            if(strlen(w)>strlen(lw))
            {
                strcpy(lw,w);
            }
            p=0;
        }
    }
    printf("Longest word = %s",lw);
    return 0;
}

Output

Enter a sentence
I am learning to code in C
Longest word = learning
video-poster