Rawsick
Rawsick

Reputation: 19

Recursively count string inside of a string java

I am supposed to recursively count how many "XX" are in a string, if there is a small x in front of a double X it should not be counted. I am not sure what I am doing wrong; I seem to be getting stuck at the very first return, I keep getting 0.

UPDATE: I have everything working it seems, but XXxXXX keeps getting counted as 1 instead of 2.

    public static int count(String s) {

        if ((s.length() < 2))
            return 0;
        int counter = 0;
        if (s.charAt(0)== 'x')
        {
        if (s.substring(0, 2).equals("xX"))
            return count(s.substring(3));

        }
        if (s.substring(0, 2).equals("XX")) {
            return 1 + count(s.substring(3));
        }
        else
            return counter + count(s.substring(1));
        }



public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner kb = new Scanner(System.in);
    System.out.println("Enter a String: ");
    String s = kb.nextLine();
    System.out.println( count(s));
}

}

Upvotes: 0

Views: 471

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Since the end index in the call of substring is exclusive, the call of substring(0, 1) will never return a two-character string; only a string consisting of the first character will be returned.

To take two characters first check that the length is two or more, and then call substring(0, 2).

Upvotes: 1

Related Questions