如何从String文本参数中找到平均字长?我有一些someMethod(String text){}。这个词由字母和数字组成。有必要考虑间隙和标点符号
public static List<String> someMethod(String text) {
String[] words = text.split("\\p{P}?[ \\t\\n\\r]+"); // split by whitespace
int count = 0;
double sum = 0;
for (String word : words) {
double wordLength = word.length();
sum += wordLength;
count++;
}
final double average = sum / count;
List<String> list = Arrays.stream(words).filter(s -> s.length()>= average).collect(Collectors.toList());
list.sort(Comparator.comparingInt(s -> Math.abs(s.length() - "intelligent".length())));
return list;
}
答案 0 :(得分:1)
使用split()方法将字符串拆分为单词(它被重载,我想我会选择一个用regexp作为参数),然后遍历数组(split()将返回)并为每个元素调用length()
P.S。在询问之前,请先做以下事情: 尝试,搜索,阅读文档