Saturday, 28 October 2017

C++ Program to reverse the words in a given string

C++ Program to reverse the words in a given string is given below.

ex:- 

Input: C++ is the easiest programming language
Output: language programming easiest the is C++


PROGRAM:

#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
vector<string> string_to_vector(string str)
{
      vector<string> arr;
      string temp="";
      for(int j=0;j<str.size();j++){
             if(str[j]==' '){
                   if(temp.size()>0){
                           arr.push_back(temp);
                           temp="";
                   }
             }else
             {
                    temp=temp+str[j];
             }
      }
      if(temp.size()>0){
             arr.push_back(temp);
      }
      reverse(arr.begin(),arr.end());
      return arr;
}
int main()
{
     int t;
     cout<<"\n\nEnter the number of test cases: \n";
     cin>>t;
     cin.ignore();
     while(t--)
     {
           string s;
           cout<<"\n\nEnter the input string:\n";
           getline(cin,s);
           vector<string> input_string;
           input_string=string_to_vector(s);
           cout<<"\nThe reversed order of words is: \n";
           for(int j=0;j<input_string.size();j++)
           {
                cout<<input_string[j];
                if(j!=input_string.size()-1){
                    cout<<" ";
                }
           }
           cout<<"\n\n";
     }
     return 0;
}


OUTPUT:




EmoticonEmoticon