Reverse a string preserving space positions | C ++ program to reverse a string preserving spaces . ; Function to reverse the string and preserve the space position ; Mark spaces in result ; Traverse input string from beginning and put characters in result from end ; Ignore spaces in input string ; ignore spaces in result . ; Driver code
#include <iostream> NEW_LINE using namespace std ; string reverses ( string str ) { int n = str . size ( ) ; string result ( n , ' \0' ) ; for ( int i = 0 ; i < n ; i ++ ) if ( str [ i ] == ' ▁ ' ) result [ i ] = ' ▁ ' ; int j = n - 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] != ' ▁ ' ) { if ( result [ j ] == ' ▁ ' ) j -- ; result [ j ] = str [ i ] ; j -- ; } } return result ; } int main ( ) { string str = " internship ▁ at ▁ geeks ▁ for ▁ geeks " ; cout << reverses ( str ) << endl ; return 0 ; }