C Program to Find the Longest Word in a String

A word is a consecutive non-whitespace character set. The C program here will find out the longest word in a given string. If multiple words are present with the same length of the longest one, it will print the first one.

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

#define MAX_STRING_LEN 1024

int main(){
  char str[MAX_STRING_LEN];
  char longest_str[MAX_STRING_LEN];
  int len;
  int i, index = 0;
  int max_wlen = 0, wlen = 0;
  
  printf("Enter a string: ");
  gets(str);
  
  len = strlen(str);
  
  for (i = 0; i <= len; i++) {
  
    if (str[i] != ' ' && str[i] != '\0') {
      wlen++;
      continue;
    }
    
    /* space or end of string */
    if (wlen > max_wlen) {
      max_wlen = wlen;
      index = i - max_wlen;
    }
    
    wlen = 0;
  }
  
  for (i = 0; i < max_wlen; i++) {
    longest_str[i] = str[index+i];
  }
  
  longest_str[i] = '\0';
  
  printf ("Longest word: %s.\n", longest_str);
  printf ("Longest word length: %d.\n", max_wlen);
  return 1;
}

This program takes a string as input. The first ‘for‘ loop traverses all the characters in the string. This loop has one extra iteration than the length of the string – to consider the last word.

The wlen variable tracks the current word length and max_wlen tracks the longest word length so far.

For every non-whitespace character, the current word length, wlen, is increased by 1.

A whitespace character is considered as a possible end of a word – unless the previous character is also a whitespace.

If a whitespace character is encountered and the current word is longer than the longest word so far (wlen > max_wlen), current word length is set as the longest one. The index variable is set as the starting index of the longest word so far. For every whitespace character wlen is reset to o – to start a fresh count for the next word.

When the first loop ends, the index becomes the starting index of the longest word. And max_wlen becomes the length of the longest word.

The second ‘for‘ loop copies the longest word to another string, longest_str. At the end the program prints the longest word with it length.

The program output:

$ ./test
Enter a string: Optimism is an occupational hazard of programming
Longest word: occupational.
Longest word length: 12.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

2 thoughts on “C Program to Find the Longest Word in a String”

Leave a Reply

Your email address will not be published. Required fields are marked *

4
0
5
1
17
5