Problem:

Given a string and a non-empty substring sub, compute recursively the number of times that sub appears in the string, without the sub strings overlapping.

strCount("catcowcat", "cat") → 2
strCount("catcowcat", "cow") → 1
strCount("catcowcat", "dog") → 0

Solution:

public int strCount(String str, String sub) {
int strlen = str.length();
int sublen = sub.length();
if (strlen < sublen) return 0;
if (str.substring(0,sublen).equals(sub))
return 1 + strCount(str.substring(sublen), sub);
else
return strCount(str.substring(1), sub);
}

1. if (!str.contains(sub)) return 0;
else return 1 + strCount(str.substring(str.indexOf(sub)+sub.length()), sub);

1. If we're going to use any old java.lang.string method, might as well defeat the purpose of this exercise entirely and not even bother with recursion:

String s=str.replace(sub,"");
return (str.length()-s.length())/sub.length();

2. public int strCount(String str, String sub) {
if(str.indexOf(sub)==-1) return 0;
if(str.indexOf(sub)!=-1)
{
return 1 + strCount(str.substring(str.indexOf(sub)+sub.length()), sub);
}
return 0;
}

3. if(str.equals("")) return 0;
if(str.startsWith(sub)) return 1 + strCount(str.substring(sub.length()), sub);
return strCount(str.substring(1), sub);

4. public int strCount(String str, String sub) {
if(str.isEmpty()){
return 0;
}
if(str.startsWith(sub)){
return 1 + strCount(str.substring(sub.length()), sub);
}
return strCount(str.substring(1), sub);
}

5. public int strCount(String str, String sub) {
if(str.isEmpty()){
return 0;
}
return (str.startsWith(sub))?
1 + strCount(str.substring(sub.length()), sub)
: strCount(str.substring(1), sub);
}