Reverse a string preserving space positions | C ++ program to implement the above approach ; Initialize two pointers as two corners ; Move both pointers toward each other ; If character at start or end is space , ignore it ; If both are not spaces , do swap ; Driver code
#include <iostream> NEW_LINE using namespace std ; void preserveSpace ( string & str ) { int n = str . length ( ) ; int start = 0 ; int end = n - 1 ; while ( start < end ) { if ( str [ start ] == ' ▁ ' ) { start ++ ; continue ; } else if ( str [ end ] == ' ▁ ' ) { end -- ; continue ; } else { swap ( str [ start ] , str [ end ] ) ; start ++ ; end -- ; } } } int main ( ) { string str = " internship ▁ at ▁ geeks ▁ for ▁ geeks " ; preserveSpace ( str ) ; cout << str ; return 0 ; }