gpt4 book ai didi

Java递归计算单词数的方法

转载 作者:行者123 更新时间:2023-12-02 07:17:04 25 4
gpt4 key购买 nike

首先我应该说这是一项让我困惑的作业,我已经纠正了讲师的一个问题:/

无论如何,我已经制作了一个使用 boolean 值、while 循环和计数器来计算单词数的方法。

但是我需要一些如何将其塑造成一种递归方法来计算字符串中的单词数量,单词由一个或多个空格分隔。

countWords("你好,这是一个例子", 0);//返回 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);
}
}

最佳答案

既然这是一项家庭作业,我就不会给你代码了。但我会向你解释解决方案。看看是否可以从中重建代码。

在该方法中,首先删除行首和行尾的空格,因为我们想忽略它。为此,请使用 trim() 方法。接下来检查该字符串是否为空字符串 (""),就像您在代码中所做的那样。如果是,则返回零,因为空字符串不包含任何单词,否则在无限循环 (while (true)) 中检查以下条件:

  • 创建一个变量来保存当前索引,该索引不是循环的本地变量,而是方法的本地变量。对于无限循环的每次迭代,检查当前字符(使用 charAt() 方法)是否不是空格以及索引是否小于字符串的长度。如果此条件成立,则增加索引变量。
  • 如果不相等,则检查索引变量是否等于字符串的长度。如果是,则返回 1,因为这意味着我们已经到达字符串的最后一个单词。
  • 如果不是,则返回 1 的总和,并递归调用从当前索引值开始查找子字符串的单词计数方法。

这应该能让你得到值(value)。如果您仍然无法做到这一点,请告诉我,我会给您来源。

编辑如果你不能使用String的trim方法,你可以自己写一个这样的。我相信它不会违反您的任何要求:

private String trim(String str) {
int beginIndex = 0;
int endIndex = str.length() - 1;

while (true) {
if (str.charAt(beginIndex) == ' ') {
beginIndex++;
} else if (str.charAt(endIndex) == ' ') {
endIndex--;
} else {
break;
}
}

return str.substring(beginIndex, endIndex);
}

编辑2如果你也无法使用length(),则修改上面的代码行int endIndex = str.length() - 1;' int endIndex = getLength(str) - 1;`并使用以下代码计算长度。

private int getLength(String str) {
int length = 0;

while (true) {
try {
str.charAt(length++);
} catch (StringIndexOutOfBoundsException e) {
break;
}
}
return --length;
}

编辑3由于这个问题是一个PITA,所以很难用语言解释。所以这是代码:

private int countWords(String searchString) {
int index = 0;
boolean beginning = true; // to check if it's the beginning of the line

if (searchString.equals("")) {
return 0;
} else {
while (true) {
try {
if (searchString.charAt(index) != ' ') {
beginning = false;
index++;
} else {
if (!beginning) {
return 1 + countWords(searchString.substring(++index));
} else {
return countWords(searchString.substring(++index));
}
}
} catch (StringIndexOutOfBoundsException e) {
if (!beginning) {
return 1;
} else {
return 0;
}
}
}
}
}

这将帮助您仅使用允许使用的方法来实现您想要的目标。

关于Java递归计算单词数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14811085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com