Sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged | A Java implementation of the approach ; Function that returns the string s in sorted form such that the positions of alphabets and numeric digits remain unchanged ; String to character array ; Sort the array ; Count of alphabets and numbers ; Get the index from where the alphabets start ; Now replace the string with sorted string ; If the position was occupied by an alphabet then replace it with alphabet ; Else replace it with a number ; Return the sorted string ; Driver code
import java . util . * ; class GFG { static String sort ( String s ) { char [ ] c = new char [ s . length ( ) + 1 ] ; c = s . toCharArray ( ) ; Arrays . sort ( c ) ; int al_c = 0 , nu_c = 0 ; while ( c [ al_c ] < 97 ) al_c ++ ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) < 97 ) s = s . substring ( 0 , i ) + c [ nu_c ++ ] + s . substring ( i + 1 ) ; else s = s . substring ( 0 , i ) + c [ al_c ++ ] + s . substring ( i + 1 ) ; } return s ; } public static void main ( String [ ] args ) { String s = " d4c3b2a1" ; System . out . println ( sort ( s ) ) ; } }