C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Shortest word in a sentence

C Program: Shortest word in a sentence

C

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[200], temp[200];

    char *token;

    char shortest[50];

    int firstWord = 1;

 

    printf("Enter a sentence: ");

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

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

 

    strcpy(temp, str); // copy sentence for tokenization

 

    token = strtok(temp, " ");

    while (token != NULL) {

        if (firstWord) {

            strcpy(shortest, token);

            firstWord = 0;

        } else if (strlen(token) < strlen(shortest)) {

            strcpy(shortest, token);

        }

        token = strtok(NULL, " ");

    }

 

    printf("\nThe shortest word is: %s\n", shortest);

 

    return 0;

}

Output

 
OUTPUT :
Enter a sentence: Programming in C is fun

The shortest word is: C


Explanation

  • The program reads a sentence using fgets().
  • Uses strtok() to split the sentence into words.
  • Compares lengths of each word using strlen().
  • Stores the word with the smallest length in shortest.