I was given the prompt below and while I have made my program count the number of times the word "hi" appears in the String given to the method, I'm not sure what to do about having the code ignore cases where the word "hi" has an x before it. Below is my prompt and below that, my code thus far. I know I need to use certain String methods but not exactly sure which one is the correct one I need for my problem nor where it needs to be placed. Any help is appreciated
Given a string, compute recursively the number of times lowercase "hi" appears in the string, however, do not count "hi" that has an 'x' immediately before them.
countHi2("ahixhi") → 1
countHi2("ahibhi") → 2
countHi2("xhixhi") → 0
Method Header: public static int countHi2(String str)
Here is the Code:
public class RecursionProblem { public static void main(String[] args) { System.out.println("Number of times the word hi appears with the exception of those with an x before it: " + countHi2("hixhihi")); }//end main public static int countHi2(String str) { //base case if(str == null) return 0; if(str.length() < 2) return 0; String first2Letters = str.substring(0, 2); if(first2Letters.equals("hi")) return 1 + countHi2(str.substring(2)); return countHi2(str.substring(1)); }//end countHi2 method }//end class
For reference, I added this to the code:
Here:else if (str.length() >= 3 && str.charAt(0) == 'x') return countHi2(str.substring(3));
and the program counted only the "hi" without an x before it as desired.public static int countHi2(String str) { if(str == null) return 0; if(str.length() < 2) return 0; String first2Letters = str.substring(0, 2); if(first2Letters.equals("hi")) return 1 + countHi2(str.substring(2)); else if (str.length() >= 3 && str.charAt(0) == 'x') return countHi2(str.substring(3)); return countHi2(str.substring(1)); }//end countHi2 method