Saturday, May 16, 2015

Move All spaces to the begining of the array (or) move all zeros to the begining of the array

class MoveSpacesToBeg {
        static public String moveSpacesToBeg(String str) {
                char[] a = str.toCharArray();

                int n = a.length-1;
                int count = n;

                for(int i=n; i>=0; i--)
                        if(a[i] != ' ')
                                a[count--] = a[i];

                while(count>=0)
                        a[count--] = ' ';

                return new String(a);
        }

        static public void main(String[] args) {
                String str = "Suresh Reddy M";
                System.out.println(str);

                str = moveSpacesToBeg(str);
                System.out.println(str);
        }
}