Find white spaces in the character array

Count non white space in the character array:
This algorithm will find out if any location in the array matches a single white space ‘ ‘. It is a very popular interview question during phone interviews. It helps to gauge if the candidate is well versed with the basics and has basic coding skills.

Algorithm:

  1. Initialize count to 0. 
  2. Run a for loop from 0 to length of array. 
  3. Compare each array location’s character with the space ‘ ‘
  4. If it matches then increment the count. 
  5. Print the count of spaces in the array.

Implementation:
public class Test  {
    static char a[] = {'a',' ', 'b',' ','c',' ', ' ', ' ', 'd'};
    public static void displayNonWhiteSpaces() {
        for(int i=0; i<a.length; i++) {
            if(a[i] != ' ') {
                System.out.println(a[i]);
            }
        }
    }

    public static void removeWhiteSpaces() {
        int k=0;
        for(int i=0; i<a.length; i++) {
            if(a[i] != ' ') {
                a[k++] = a[i];
                if(k<i) {
                    a[i] = ' ';
                }
            }
        }

        System.out.println("Length " + a.length);

        for(int i=0; i<a.length; i++) {
            System.out.print("\n" + a[i]);
        }

    }

    public static void main(String args[]) {
        displayNonWhiteSpaces();
        removeWhiteSpaces();
    }
}

Complexity:

No comments:

Post a Comment

NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...