Describe the following two functions and whether they perform the same task –
public int Jane1(String input, char aChar) {
int count = 0;
int index = input.indexOf(aChar);
while (index >= 0) {
count++;
index = input.indexOf(aChar, index + 1);
}
return count;
}
public int Jane3(String input, char aChar) {
int index = input.indexOf(aChar);
if (index < 0) return 0;
return Jane3(input.substring(index + 1), aChar) + 1;
}
I think they don’t perform the same task, however I’m not sure of the explanation. Jane3 function uses a recursive call to return the length of the String input, where as Jane1 returns the length of the String. Struggling to get my head around the difference between returning sub string (which I think is a String result), and index of?
They both perform the same task. Count how many times
aCharappears atinput. The first one uses an overloaded version ofindexOfand a loop to achieve the result. The second version will split the input at the first occurrence ofaCharand call itself recursively for the second halve. The result is an integer (0 if no occurrence happens, or 1 + the number of times the character was found in the second halve).PS: Why don’t you write a main class and run / debug both of those methods for different inputs? It is the best way to learn…