Reverse words in a given string | Set 2 | C ++ Program to implement the above approach ; Function to reverse the words of a given string ; Stack to store each word of the string ; Store the whole string in string stream ; Push each word of the string into the stack ; Print the string in reverse order of the words ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printRev ( string str ) { stack < string > st ; stringstream ss ( str ) ; string temp ; while ( getline ( ss , temp , ' ▁ ' ) ) { st . push ( temp ) ; } while ( ! st . empty ( ) ) { cout << st . top ( ) << " ▁ " ; st . pop ( ) ; } } int main ( ) { string str ; str = " geeks ▁ quiz ▁ practice ▁ code " ; printRev ( str ) ; return 0 ; }