Using Java use recursion to write a method int countLetterSt

Using Java, use recursion to write a method: int countLetter(String s, char c) which returns the number of times the letter c occurs in the string s. For instance:
countLetter(\"hi there\", \'h\') should be 2
countLetter(\"Mississippi\", \'i\') should be 4
countLetter(\"Marquette\", \'s\') should be 0
To help with your recursive design, remember that a non-empty string S can be separated into a first letter, say F, and a substring of the remaining letters, say R. Then, the number of times a character c occurs in S is equal to countLetter(R, c) if c is not equal to F and is 1 + countLetter(R, c) if c *is* equal to F.
write a simple test driver which reads a string and a character and prints the count.

Solution

public class HelloWorld{
    static int count = 0, i=0;
     public static void main(String []args){
    
        countLetter(\"hi there\", \'h\');
        System.out.println(\"count: \" +count);
        count = i = 0;
        countLetter(\"Mississippi\", \'i\');
        System.out.println(\"count: \"+count);
        count = i = 0;
        countLetter(\"Marquette\", \'s\');
        System.out.println(\"count: \"+count);
     }
    public static int countLetter(String s, char c){
            
            if (s.charAt(i) == \'\\0\' || s.equals(\"\")) {
                return -1;
            }
            if (c == s.charAt(i++))
                count++;
                 
            countLetter(s, c);
            return 0;
    }
}

Using Java, use recursion to write a method: int countLetter(String s, char c) which returns the number of times the letter c occurs in the string s. For instan

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site