Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program to Find the Shortest Word in a String

$
0
0

A word is a consecutive non-whitespace character set. The C program here will find out the shortest word in a given string. If multiple words are present with the same length of the shortest 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 shortest_str[MAX_STRING_LEN];
  int len;
  int i, index = 0;
  int min_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;
    }
    
    if (min_wlen == 0 || wlen < min_wlen) {
      min_wlen = wlen;
      index = i - min_wlen;
    }
    
    wlen = 0;
  }
  
  for (i = 0; i < min_wlen; i++) {
    shortest_str[i] = str[index+i];
  }
  
  shortest_str[i] = '\0';
  
  printf ("Shortest word: %s.\n", shortest_str);
  printf ("Shortest word length: %d.\n", min_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 min_wlen tracks the shortest 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 shorter than the shortest word so far (wlen < max_wlen), current word length is set as the shortest one. The index variable is set as the starting index of the shortest 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 shortest word. And min_wlen becomes the length of the shortest word.

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

The program output:

$ ./test
Enter a string: Simplicity is the soul of efficiency
Shortest word: is.
Shortest word length: 2.

The post C Program to Find the Shortest Word in a String appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>