Reverse a string preserving space positions | Java 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 function
public class ReverseStringPreserveSpace { static void reverses ( String str ) { char [ ] inputArray = str . toCharArray ( ) ; char [ ] result = new char [ inputArray . length ] ; for ( int i = 0 ; i < inputArray . length ; i ++ ) { if ( inputArray [ i ] == ' ▁ ' ) { result [ i ] = ' ▁ ' ; } } int j = result . length - 1 ; for ( int i = 0 ; i < inputArray . length ; i ++ ) { if ( inputArray [ i ] != ' ▁ ' ) { if ( result [ j ] == ' ▁ ' ) { j -- ; } result [ j ] = inputArray [ i ] ; j -- ; } } System . out . println ( String . valueOf ( result ) ) ; } public static void main ( String [ ] args ) { reverses ( " internship ▁ at ▁ geeks ▁ for ▁ geeks " ) ; } }