Find Smallest and Largest Word of the String

Find Smallest and Largest Word of the String” is again a basic problem of string data structure. Here, we are given a string containing some words and our task is to find the largest and smallest word of the string.

Example:

INPUT:
Help Me Study Bro
OUTPUT:
Smallest Word: Me
Largest Word: Study

The steps required to find the smallest and largest word of the string are:

  1. Separate each word of the string (stringstream can be used in C++ to do the same task).
  2. Count each word length. Store the largest and smallest while scanning.
  3. Print smallest and largest word.

C++ Program to find the smallest and largest word of the string is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    string str;  
    /* Scan the String */  
    cout<<"Enter a string:\n";  
    getline(cin,str);  
      
    /* Word Variable to store word */  
    string word;  
      
    /* Making Stirng stream */  
    stringstream iss(str);   
      
    string smallest;  
    string largest;  
    int flag = 0;  
      
    /* Scanning each word of the string and 
       storing the result in temporary variables */  
    while (iss >> word)   
    {  
        if(flag == 0)  
        {  
            smallest = word;  
            largest = word;  
            flag = 1;  
        }  
        else  
        {  
            if(smallest.length() > word.length())  
            smallest = word;  
            else if(word.length() > largest.length())  
            largest = word;  
        }  
    }  
    /* Printing the Result */  
    cout<<"Smallest Word: "<<smallest;  
    cout<<"\nLargest Word: "<<largest;  
}  

OUTPUT:
Enter a string: 
Help Me Study Bro
Smallest Word: Me
Largest Word: Study

You may also like...

Leave a Reply

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