program to count a particular word occurrence in a Sequence of string without using loop

Program:

public class Main {
   static int count = 0;
    String search;
    int len;
    String[] str;
    Main(String[] s,String srch){
str = s;
search = srch;
len = s.length;
    }

    int call_me(int len) {

        if (len < 1) // base case
        {
            return count;
        } else if (str[len].equals(search)) {
            ++count;
        }
        return call_me(len - 1);
    }

    public static void main(String[] args) {
        Main obj;
        String[] str = {"this","is","a","string","and","a","sequence","of","a","string","arr"};
        obj = new Main(str,"a");
        System.out.println(obj.search+" occurred "+obj.call_me(obj.len-1)+" times");

    }
}

Output:

a occurred 3 times

Leave a Reply