Java 字符串函数
描述以下两个函数以及它们是否执行相同的任务 -
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;
}
我认为它们不执行相同的任务,但我不确定解释。 Jane3 函数使用递归调用返回字符串输入的长度,而 Jane1 返回字符串的长度。努力弄清楚返回子字符串(我认为是字符串结果)和索引之间的区别?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
他们都执行相同的任务。计算
aChar
在input
中出现的次数。第一个使用indexOf
的重载版本和循环来获得结果。第二个版本将在第一次出现aChar
时分割输入,并在第二部分递归地调用自身。结果是一个整数(如果没有出现则为 0,或者 1 + 在后半部分中找到该字符的次数)。PS:为什么不编写一个主类并针对不同的输入运行/调试这两个方法?这是最好的学习方式...
They both perform the same task. Count how many times
aChar
appears atinput
. The first one uses an overloaded version ofindexOf
and a loop to achieve the result. The second version will split the input at the first occurrence ofaChar
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 使用 while 循环,而 Jane3 使用递归。这应该是一个好的开始。两者都返回字符串中字符出现的次数。
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
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.
两者显示相同的输出:
1. 方法 1
2. 方式 2
PS:您尝试运行代码并使用 o/p 检查吗?
Both show the same output :
1. Way 1
2. Way 2
PS : You tried running the code and checking with o/p ?