【发布时间】:2021-07-31 06:57:21
【问题描述】:
只是想知道如何在没有任何循环的情况下将此代码切换到不同的代码,但仍保持其所做的事情。仅使用 if\switch 并修复它实际上它似乎有效
public static int countWords(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
【问题讨论】:
-
没有任何循环,但仍然保持它正在做的事情。只使用 if\switch 那是 not 可能的。但你可以做
return s.split("\\s+").length; -
试试
s.split("\\PL+"),它将字符串s拆分为任何非字符。 -
“它实际上似乎有效”——然后发布 minimal reproducible example 并告诉我们它是如何无效的
-
@A.B 你能解释一下你想要实现的目标吗?例如,我使用字符串“aaddrr12345;2C”运行您的代码,结果得到 2。为什么?你想数什么?
-
@AB 例如,在字符串中我尝试了 "aaddrr12345;2C" 我在字符串的中间数了 7 个非字母,在末尾加上一个字母,所以预期的结果是 8,你为什么要 2 来代替?
标签: java loops if-statement switch-statement