guys I'm having some problems with something really basic. I have a suggested solution to a problem that looks like (below) but I don't understand how the static argument of countX == str.substring(1) is supposed to search the entire String, the argument is a static 1 (?!?!) :
public int countX(String str) {
if (str.length() == 0) return 0;
if (str.charAt(0) == 'x') return 1 + countX(str.substring(1));
return countX(str.substring(1));
}
Instead I thought of this solution before looking up for the solution but can't figure out how to identify the right most char of the substring for comparison with the searched char 'x' (line : 3)
public int countX(String str) {
if (str.length()>0) {
if (str.charAt(str.substring(str.length()-1) == 'x'))
return countX (str.substring(str.length()-1)) + 1;
else
return countX (str.substring(str.length() -1)
}
else
return 0;
}
Any suggestion for my ignorance about the first solution and my mistake on the second ?Thanks in advance
substring
? – GBlodgettsubstring(1)
will return theString
minus the first char. So if you do"abcd".substring(1);
it will return"bcd"
– GBlodgett