Just flip the values
if ( str . charAt ( k ) == ' ' ) str = str . substring ( 0 , k ) + " " + str . substring ( k + 1 , str . length ) ; else str = str . substring ( 0 , k ) + " " + str . substring ( k + 1 , str . length ) ; }