统计任意一个字符串中,英文单词的总数,最长的单词长度,最短的单词长度,单词的平均长度(用JAVA写哦)例如:“ab+12cd*123dfg%&()as23BG”,则单词总数为5,最长长度为4,最短单词长度为2,平均长度为2.4 则单词总数为5,最长长度为4,最短单词长度为2,平均长度为2.4 怎么算啊 单词总数为5这些怎么算啊
2019-06-14
统计任意一个字符串中,英文单词的总数,最长的单词长度,最短的单词长度,单词的平均长度(用JAVA写哦)例如:“ab+12cd*123dfg%&()as23BG”,则单词总数为5,最长长度为4,最短单词长度为2,平均长度为2.4
则单词总数为5,最长长度为4,最短单词长度为2,平均长度为2.4 怎么算啊 单词总数为5这些怎么算啊
优质解答
首先,你的例子string中最长的是dfg,长度是3,不是4,平均也是2.2
然后是代码
final String regex = "[^a-zA-Z]+";
String s = "ab+12cd*123dfg%&()as23BG";
String[] words = s.split(regex);
int min = Integer.MAX_VALUE,max = 0,total = 0,length;
for (String word :words) {
length = word.length();
total += length;
min = Math.min(min,length);
max = Math.max(max,length);
}
System.out.printf("Shortest length:%d",min);
System.out.printf("Longest length:%d",max);
System.out.printf("Average length:%f",((double) total) / words.length);
首先,你的例子string中最长的是dfg,长度是3,不是4,平均也是2.2
然后是代码
final String regex = "[^a-zA-Z]+";
String s = "ab+12cd*123dfg%&()as23BG";
String[] words = s.split(regex);
int min = Integer.MAX_VALUE,max = 0,total = 0,length;
for (String word :words) {
length = word.length();
total += length;
min = Math.min(min,length);
max = Math.max(max,length);
}
System.out.printf("Shortest length:%d",min);
System.out.printf("Longest length:%d",max);
System.out.printf("Average length:%f",((double) total) / words.length);