用java求任意一个字符串中英文单词的总数,最长单词的长度,最短单词的长度

如题所述

你这个字符串有要求吗,是必须都是英文?
是这样的 123ad123adasdvfZ233
还是都是字母加空格 asdf dfsdf dfdsopp ??追问

就是第一个那种的就行

追答

public static void main(String[] args) {
String a = "asdf23/sdfsd34sdfs32ae325./,'asda;sdf'zxcqaaaa123";
char[] b = a.toCharArray();
for(int i =0;itemp_i.length()&&shortWord.length()>temp_i.length()){
shortWord = temp_i;
}
}else{
continue;
}
}
}else{
continue;
}
}
System.out.println("sum:" +sum);
System.out.println("long is :" +longWord+" ;size :"+longWord.length());
System.out.println("short is :" +shortWord+" ;size :"+shortWord.length());
}
写得有点乱,但基本就这个意思,能完全按照你的要求来

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-04-07
public static void main(String[] args) {
String sentense="a b cd efg hijkl m n";//句子假设以空格分隔

String[] words=sentense.split(" "); //分出单词

int count=words.length; //获取句子中单词总数

int maxLength=0; //最长单词长度
int minLength=999; //最短单词长度

for(String word:words)
{
maxLength=Math.max(maxLength, word.length());
minLength=Math.min(minLength, word.length());
}

System.out.println("一共有"+count+"个单词");
System.out.println("最长的单词长度是:"+maxLength);
System.out.println("最短的单词长度是:"+minLength);
}追问

能在加个求平均长度的吗?就在这个的基础上加一下

追答

public static void main(String[] args) {
String sentense="a b cd efg hijkl m n";//句子假设以空格分隔

String[] words=sentense.split(" "); //分出单词

int count=words.length; //获取句子中单词总数

int maxLength=0; //最长单词长度
int minLength=999; //最短单词长度

int avgLength=0; //平均长度

for(String word:words)
{
avgLength+=word.length(); //先计算总长
maxLength=Math.max(maxLength, word.length());
minLength=Math.min(minLength, word.length());
}

avgLength=avgLength/count; //计算平均长度

System.out.println("一共有"+count+"个单词");
System.out.println("最长的单词长度是:"+maxLength);
System.out.println("最短的单词长度是:"+minLength);
System.out.println("平均的单词长度是:"+avgLength);
}

本回答被提问者采纳