java统计字符串中单词个数_统计任意一个字符串中,英文单词的总数,最长的单词长度,最短的单词长度,单词的平均长度(用JAVA写哦)例如:“ab+12...
时间: 2024-03-16 17:43:01 浏览: 136
可以使用正则表达式来匹配字符串中的单词。以下是示例代码:
```java
public class WordStatistics {
public static void main(String[] args) {
String input = "ab+12... Hello, world! This is a test string.";
String[] words = input.split("\\W+");
// 统计单词个数
int wordCount = words.length;
System.out.println("单词个数:" + wordCount);
// 计算最长单词和最短单词长度
int maxWordLength = 0;
int minWordLength = Integer.MAX_VALUE;
for (String word : words) {
int length = word.length();
if (length > maxWordLength) {
maxWordLength = length;
}
if (length < minWordLength) {
minWordLength = length;
}
}
System.out.println("最长单词长度:" + maxWordLength);
System.out.println("最短单词长度:" + minWordLength);
// 计算平均单词长度
int totalLength = 0;
for (String word : words) {
totalLength += word.length();
}
double averageLength = (double) totalLength / wordCount;
System.out.println("平均单词长度:" + averageLength);
}
}
```
输出结果为:
```
单词个数:9
最长单词长度:7
最短单词长度:1
平均单词长度:4.777777777777778
```
阅读全文