Reverse a string preserving space positions | Java 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
import java . io . * ; import java . util . * ; class GFG { public static void preserveSpace ( String str ) { int n = str . length ( ) ; int start = 0 ; int end = n - 1 ; char [ ] Str = str . toCharArray ( ) ; while ( start < end ) { if ( Str [ start ] == ' ▁ ' ) { start ++ ; continue ; } else if ( Str [ end ] == ' ▁ ' ) { end -- ; continue ; } else { char temp = Str [ start ] ; Str [ start ] = Str [ end ] ; Str [ end ] = temp ; start ++ ; end -- ; } } System . out . println ( String . valueOf ( Str ) ) ; } public static void main ( String [ ] args ) { String str = " internship ▁ at ▁ geeks ▁ for ▁ geeks " ; preserveSpace ( str ) ; } }