Find Smallest and Largest Word in String
“Find Smallest and Largest Word in String” is again a basic problem of string data structure. Here, we are given a string containing some words and our task is to write a program to find smallest and largest word in string.
Example:
INPUT: Help Me Study Bro OUTPUT: Smallest Word: Me Largest Word: Study
The steps required to find smallest and largest word in string are:
- Separate each word of the string. (stringstream can be used in C++ to do the same task).
- Count each word length. Store the largest and smallest while scanning.
- Print smallest and largest word.
C++ Program to Find Smallest and Largest Word in String is as follows:
/* Program to Find Smallest and Largest Word in String */
#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
Related Posts:
- Program to find Most Frequent Character of the String.
- Program to Remove all the blank spaces from the String.
- Program to check if String is isogram or not.
- Program to Reverse Each word of the String.
- Program to Print All the Substring of the Given String.
- Program to find longest palindromic Substring.
- Program to check Anagram Strings.
- Program to check whether two Strings are Rotation of each other or not.
- Program to check Palindromic Anagram.
- Program to print all the Palindromic Substring of the String.
- Program to check Panagram String.
- Program to find first non-repeating character of the String.
- Program to check Idempotent Matrix.
- Program to check Involuntary Matrix.
- Program to print matrix in zig-zag order.
- Program to print matrix in spiral order.
- Program to sort a matrix.
- Detect a Loop in a Linked List.
- Find the Length of the Loop present in the Linked List.
- Detect and Remove Loop from a Linked List.