Using recursion to count substrings (with exceptions to the rule) in Java I am going through the CodingBat exercises for Java. Here is the one I have just finished:


  Given a string, compute recursively the number of times lowercase hi appears in the string, however do not count hi that have an x immedately before them. 


And here is my code:

public int countHi2(String str) {

    if (str.length() &lt; 3) {
        return str.equals("hi") ? 1 : 0;
    }

    if (str.substring(0, 3).equals("xhi")) {
        return countHi2(str.substring(2));
    }

    if (str.substring(0, 2).equals("hi")) {
        return 1 + countHi2(str.substring(2));
    } else {
        return countHi2(str.substring(1));
    }

}


This is the first in a recursion exercise which I have needed to change the base case to accommodate how the rest of the code works. I originally made it so that whenever an x is reached, it returns a substring from 2 (because the following hi is irrelevant), but of course, this is useless when there are two x's adjacent to one another.

I am still getting used to the idea of recursion, so I would like to know if this is a 'good' solution or not. Can it be made more efficient?
Similar to @Ben Aaronson above but uses indexOf() instead of startsWith()

public int countHi2(String str) {
    int pos = str.indexOf("hi");
    if (pos == -1) {
       return 0;
    }
    int increment = (pos == 0 || str.charAt(pos-1) != 'x') 
                      ? 1
                      : 0;   
    return countHi2(str.substring(pos+2))
           + increment;
}