Tuesday, January 14, 2014

Can you write code without using Iterator to count characters in a string?

Q. Write a sample code that will count the number of "Z"s in a given text? Show both iterative and recursive approaches?
A.

Iterative method:


public class Iteration {
    public int countA(String input) {
        if (input == null || input.length( ) == 0) {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < input.length( ); i++) {
            if(input.substring(i, i+1).equals("Z")){
                count++;
            }
        }
        return count;
    }
    public static void main(String[ ] args) {
          System.out.println(new Iteration( ).countA("ZZZ"));     // Ans.3
    }


Recursive method:


public class RecursiveCall {
    public int countA(String input) {
        
        // exit condition – recursive calls must have an exit condition
        if (input == null || input.length( ) == 0) {
            return 0;
        }
        int count = 0;
          
        //check first character of the input
        if (input.substring(0, 1).equals("Z")) {
            count = 1;
        }
         
        //recursive call to evaluate rest of the input
        //(i.e.  2nd character onwards)
        return count + countA(input.substring(1));
    }
    public static void main(String[ ] args) {
        System.out.println(new RecursiveCall( ).countA("ZZZ"));    // Ans. 3
    }
}

No comments:

Post a Comment