Program to find Smallest and Largest Word in a String in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the smallest and largest word in a string.

For this we will be provided with a string. Our task is to find the smallest and largest word in that string on the basis of length.

Example

 Live Demo

#include<iostream>
#include<cstring>
using namespace std;
void minMaxLengthWords(string input, string &minWord, string &maxWord) {
   int len = input.length();
   int si = 0, ei = 0;
   int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0;
   while (ei <= len) {
      if (ei < len && input[ei] != ' ')
         ei++;
      else {
         int curr_length = ei - si;
         if (curr_length < min_length) {
            min_length = curr_length;
            min_start_index = si;
         }
         if (curr_length > max_length) {
            max_length = curr_length;
            max_start_index = si;
         }
         ei++;
         si = ei;
      }
   }
   //storing minimum and maximum words
   minWord = input.substr(min_start_index, min_length);
   maxWord = input.substr(max_start_index, max_length);
}
int main() {
string a = "An apple a day keeps the doctor away";
   string minWord, maxWord;
   minMaxLengthWords(a, minWord, maxWord);
   cout << "Minimum length word: "
   << minWord << endl
   << "Maximum length word: "
   << maxWord << endl;
   return 0;
}

Output

Minimum length word: a
Maximum length word: doctor
raja
Published on 19-May-2020 15:28:22
Advertisements