Interview Question & Answer – 7

By | October 5, 2018

Question

Write a recursive program to count the number of “a”s in a string.

Solution

package com.test;

public class CountAs {

	static int countA(String str) {
		if (str.length() == 0) {
			return 0;
		}
		int count = 0;
		if (str.substring(0, 1).equals("a")) {
			count = 1;
		}
		return count + countA(str.substring(1));
	}

	public static void main(String[] args) {
		int count = countA("Hello how are you. I am from India.");
		System.out.println("Count A :: " + count);
	}
}

Leave a Reply

Your email address will not be published.