作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
public static String number(String words) {
int length = words.length;
int total = 0;
while(int index < length) {
total = total + 1;
index = index + 1;
}
}
String output;
output = total + " word";
return output;
}
示例输出如下:
numberOfWords("Hello whats up?")
3 word
这适用于所有正确的句子,但我必须考虑到错误的输入,例如:
"Hi my name is bob"
,这大概有三十多个字。还有
" "
,应该是 0 个字。有没有简单的方法可以使第一个示例成为“嗨,我的名字是鲍勃”?
最佳答案
你可以做类似this的事情:
String trimmed = text.trim();
int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
或者(最简单的方法):
use str.replaceAll("\\s+"," ");
关于java - 简单的java程序,查找句子中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46329263/
我是一名优秀的程序员,十分优秀!