Luca Conin
Luca Conin

Reputation: 33

Recursive count of a char in Str -- Java

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

Upvotes: 0

Views: 119

Answers (1)

Stefan Freitag
Stefan Freitag

Reputation: 3608

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.

Upvotes: 1

Related Questions