【发布时间】:2013-02-11 11:12:44
【问题描述】:
首先我应该说这是一个让我感到困惑的作业,我已经纠正了讲师的一个问题:/
无论如何,我已经创建了一个使用布尔值、while 循环和计数器计算单词的方法。
但是我需要了解如何将其转化为一种计算字符串中单词数量的递归方法,一个单词由一个或多个空格分隔。
countWords(" hello this is an example", 0); // returns 5
如您所见,唯一的参数是 countWords(String s, int i) 使其变得更加困难。
此外,在该方法中,我仅限于使用这三种方法 s.charAt(0)、s.substring(1) 和 s.equals("") 再次使它更让人头疼:)
这是我使用 while 循环编写的非递归方法:
public static int countWords(String s) {
int words = 0;
boolean spaceBefore = true;
boolean spaceCurrently = false;
while(true) {
if (s.equals(""))
return words;
if (s.charAt(0) == ' ')
spaceCurrently = true;
else
spaceCurrently = false;
if (spaceBefore && !spaceCurrently)
words++;
spaceBefore = spaceCurrently;
s = s.substring(1);
}
}
【问题讨论】:
-
发布您的第一个方法。以及您为递归代码尝试过的任何代码。
-
提示:字数=空格数+1。字数 = 1 + 字符串中第一个空格后的字数。
-
@MrSmith42
a word is delimited by one or **many** spaces -
Spoon 先生要求的发布方法
-
@fvu:好的,但这不会改变算法思想。
标签: java recursion count words