C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Longest word in a sentence

C Program: Longest word in a sentence

C

#include <stdio.h>

#include <string.h>

#include <ctype.h>

 

int main() {

    char str[200], word[50], longest[50];

    int i = 0, j = 0, maxLen = 0, len = 0;

 

    printf("Enter a sentence: ");

    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0';  // remove newline

 

    while (1) {

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

            word[j++] = str[i];

        } else {

            word[j] = '\0';  // end current word

            len = strlen(word);

            if (len > maxLen) {

                maxLen = len;

                strcpy(longest, word);

            }

            j = 0; // reset for next word

        }

 

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

            break;

 

        i++;

    }

 

    printf("\nLongest word: %s\n", longest);

    printf("Length: %d\n", maxLen);

 

    return 0;

}

Output

 
OUTPUT :
Enter a sentence: Programming in C is enjoyable

Longest word: Programming
Length: 11

Explanation

  • The program reads a sentence using fgets().
  • It scans character by character, extracting words separated by spaces.
  • For each word, it checks its length and updates the longest one if needed.