gpt4 book ai didi

java - 简单的java程序,查找句子中的单词数

转载 作者:行者123 更新时间:2023-12-01 20:13:15 26 4
gpt4 key购买 nike

  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/

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