Remove spaces from a given string | An efficient Java program to remove all spaces from a string ; Function to remove all spaces from a given string ; To keep track of non - space character count ; Traverse the given string . If current character is not space , then place it at index ' count + + ' ; str [ count ++ ] = str [ i ] ; here count is incremented ; Driver code
class GFG { static int removeSpaces ( char [ ] str ) { int count = 0 ; for ( int i = 0 ; i < str . length ; i ++ ) if ( str [ i ] != ' ▁ ' ) return count ; } public static void main ( String [ ] args ) { char str [ ] = " g ▁ eeks ▁ for ▁ ge ▁ eeks ▁ " . toCharArray ( ) ; int i = removeSpaces ( str ) ; System . out . println ( String . valueOf ( str ) . subSequence ( 0 , i ) ) ; } }