Using Java, use recursion to write a method: int countLetter(String s, char c) w
ID: 3800150 • Letter: U
Question
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.
Explanation / Answer
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) == '' || s.equals("")) {
return -1;
}
if (c == s.charAt(i++))
count++;
countLetter(s, c);
return 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.