Java String Function
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.index开发者_如何学运维Of(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 aChar
appears at input
. The first one uses an overloaded version of indexOf
and a loop to achieve the result. The second version will split the input at the first occurrence of aChar
and 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...
Jane1 uses a while loop where Jane3 uses recursion. This should be a good start. Both return the number of occurences of a character in a string.
What I would suggest you do, is to take a string (make something up), and with pen and paper, work through each method. For example
Jane1("This is my homework", 'i');
Jane3("This is my homework", 'i');
And see what you get. You will work through that both give the same result, one with recursion, and one using a loop. Working through on pen and paper will help you understand it, so you can explain to your lecturer what each method is trying to achieve.
Both show the same output :
1. Way 1
2. Way 2
PS : You tried running the code and checking with o/p ?
精彩评论