Reverse individual words | C ++ program to reverse individual words in a given string using STL list ; reverses individual words of a string ; Traverse given string and push all characters to stack until we see a space . ; When we see a space , we print contents of stack . ; Since there may not be space after last word . ; Driver program to test function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void reverseWords ( string str ) { stack < char > st ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { if ( str [ i ] != ' ▁ ' ) st . push ( str [ i ] ) ; else { while ( st . empty ( ) == false ) { cout << st . top ( ) ; st . pop ( ) ; } cout << " ▁ " ; } } while ( st . empty ( ) == false ) { cout << st . top ( ) ; st . pop ( ) ; } } int main ( ) { string str = " Geeks ▁ for ▁ Geeks " ; reverseWords ( str ) ; return 0 ; }