Skip to content

C++ program to reverse sentence without reversing words

Program to reverse sentence without reversing words in C++ with simple algorithms using stack. This algorithm also handles spaces and special characters in the sentence or a given string.

TEST CASES:
Input: Hello World!!!
Output: !!!World Hello

Input:    Hello             World           !!!
Output: !!!          World             Hello

Algorithm: Push spaces and each words in a stack and then pop all.

Traverse the string and construct each word till a space is found and push it to the stack. If space found then it also need to be pushed in the stack. If there are multiple spaces between words then they also need to be pushed in the stack.

So, stack will contains both spaces and words. Pop the stack within a loop and print reversed sentence.

C++ Program Example to reverse sentence


#include<stack>
#include <iostream>
using namespace std;

int main(){

      std::string str = "Hello How are you ?";
      string result =" ";

      //create a stack that holds string value
      std::stack<string> s;

      for(int i=0; i<= str.length(); ++i)
      {
            if(str[i] == ' ' || str[i] == '\0'){

                  s.push(result);
                  result =" ";   
            }else{
                  result += str[i];
            }
      }

      while(!s.empty()){
            std::string o = s.top();
            cout<<o.c_str(); 
            s.pop();
      }

      return 0;

}

If you want to use same initial string variable, then clear it and fill it with stack popped elements. for example,


str.erase();
      while(!s.empty()){

            std::string o = s.top();
            str.append(o.c_str());
            s.pop();
      }
      cout<<str.c_str();

Published inC++ Programming Examples