0
votes

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

1
Did you read the docs for substring?GBlodgett
yeah and couldn't find a way to define what I call String.substring.length ()Luca Conin
substring(1) will return the String minus the first char. So if you do "abcd".substring(1); it will return "bcd"GBlodgett
got that but what I can't understand is why the subsequent recursive call let's say of abcd.substring(1); call "cd" this time. Should I just take it as it is (it's the way substring works) ?Luca Conin
owwwww just realized that the recursive call is done on already a substring after the first time so that's why it keeps chopping off the string. Thanks your analogy just started the right thought chain :))Luca Conin

1 Answers

0
votes

Let me explain the first solution. The idea is to split the string into its first character and the rest.

  • If the first character is an x we have to add 1 to the count and continue recursively.
  • If it is not an x we have to add nothing and continue recursively.
  • For the rest: let us split this up again into its first character and its rest (aka recursion)

To catch also the situation of an empty string, the length of the input is checked first. If length is 0, then the count of x is zero.