【发布时间】:2022-01-07 16:45:21
【问题描述】:
每个人。我有一个任务 - 只要单词长度为 5 个或更多字母,就反转句子中的每个单词。该程序一直在处理大多数单词,但在几次之后,这些单词不包括在内。有谁知道为什么会这样?代码如下:
public static int wordCount(String str) {
int count = 0;
for(int i = 0; i < str.length(); i++) if(str.charAt(i) == ' ') count++;
return count + 1;
}
这只是为我计算字数,我稍后会在 for 循环中使用它来循环所有单词。
public static String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
sb.append(stack.pop());
}
return sb.toString();
}
这会反转单个字符串。这不是我颠倒某些单词的地方——这会颠倒一个字符串。从https://stackoverflow.com/a/33458528/16818831“借来的”。
最后,实际功能:
public static String spinWords(String sentence) {
String ans = "";
for(int i = 0; i <= wordCount(sentence); i++) {
if(sentence.substring(0, sentence.indexOf(' ')).length() >= 5) {
ans += reverseString(sentence.substring(0, sentence.indexOf(' '))) + " ";
sentence = sentence.substring(sentence.indexOf(' ') + 1);
} else {
ans += sentence.substring(0, sentence.indexOf(' ')) + " ";
sentence = sentence.substring(sentence.indexOf(' ') + 1);
}
}
return ans;
}
这可能是我的错误所在。我想知道为什么有些词被省略了。以防万一,这是我的主要方法:
public static void main(String[] args) {
System.out.println(spinWords("Why, hello there!"));
System.out.println(spinWords("The weather is mighty fine today!"));
}
让我知道为什么会发生这种情况。谢谢!
【问题讨论】:
-
你尝试调试了吗?
-
@shmosel 抱歉,我没有说明到目前为止我为解决此问题所做的工作。我在 spinWords 函数中更改了 for 循环中的条件,我试图查看是否有任何双簧管,一堆东西。很多这样的“解决方案”只是让输出进一步离题。
-
您能否确认
Why, hello there!的预期输出是Why, olleh !ereht -
如果你使用
"Why, hello there!".split (" ");,你的代码也会简单很多 -
把 wordCount(sentence) 作为一个单独的变量