java中统计任意一个字符串中的英文单词总数、最长单词的长度、最短单词的长度、单词的平均长度
时间: 2024-03-16 10:41:13 浏览: 96
java基础编程:统计出给定字符串的英文字母、空格、数字和其它字符的个数
您可以使用以下代码来实现统计任意一个字符串中的英文单词总数、最长单词的长度、最短单词的长度、单词的平均长度:
```java
public static void analyzeWords(String str) {
if (str == null || str.isEmpty()) {
System.out.println("The input string is null or empty.");
return;
}
// Split the input string into an array of words
String[] words = str.split("\\s+");
int wordCount = words.length;
int shortestWordLength = Integer.MAX_VALUE;
int longestWordLength = 0;
int totalWordLength = 0;
// Iterate over each word to determine its length
for (String word : words) {
// Remove any non-alphabetic characters from the word
word = word.replaceAll("[^a-zA-Z]", "");
if (word.isEmpty()) {
// Skip over any empty words
continue;
}
int wordLength = word.length();
totalWordLength += wordLength;
if (wordLength < shortestWordLength) {
shortestWordLength = wordLength;
}
if (wordLength > longestWordLength) {
longestWordLength = wordLength;
}
}
double averageWordLength = (double) totalWordLength / wordCount;
// Output the results
System.out.println("Word count: " + wordCount);
System.out.println("Shortest word length: " + shortestWordLength);
System.out.println("Longest word length: " + longestWordLength);
System.out.println("Average word length: " + averageWordLength);
}
```
在上述代码中,我们首先将输入字符串按照空格分割成一个单词数组,然后遍历每一个单词。对于每一个单词,我们先将其剔除掉非字母字符,然后统计其长度。同时,我们也记录下最短单词的长度、最长单词的长度和所有单词的总长度。最后,我们根据这些统计数据计算出单词的平均长度,并将所有结果输出到控制台。
请注意,本代码假定输入字符串中的单词均为英文单词,如果有其他语言的单词或者标点符号,可能需要进行一些额外的处理。
阅读全文