可以利用String.split(" ")把各个单词区分开,返回的数组存放各个单独的单词,因为单词一般以空格分隔。
其实。这种算法还有缺陷,它把标点符号也算进去了。
你可以事先对输入的字符串处理,去除所有的 . , ! ' : - 等等标点符号再用这种方法统计。
举例如下
//注意把文件名与公共类名保持一致,如Tongji.java,区分大小写
public class Tongji {
/**
* @param args
*/
public static void main(String[] args) {
//指定的英文
String input="Tom Jack Jerry Tomcat Nokia";
String[] allword=input.split(" ");//用空格拆分各个单词。
int three=0;
int four=0;
int five=0;
int six=0;
//遍历所有单词,统计
for(String word:allword) {
if(word.length()==3)
++three;
else if(word.length()==4)
++four;
else if(word.length()==5)
++five;
else if(word.length()==6)
++six;
}
//计算百分比
float percent_three=(three*1.0f/allword.length)*100;
float percent_four=(four*1.0f/allword.length)*100;
float percent_five=(five*1.0f/allword.length)*100;
float percent_six=(six*1.0f/allword.length)*100;
//输出
System.out.println("共计单词"+allword.length+"个");
System.out.println("3字单词个数为:"+three+" ,百分比:"+percent_three+"%");
System.out.println("4字单词个数为:"+four+" ,百分比:"+percent_four+"%");
System.out.println("3字单词个数为:"+five+" ,百分比:"+percent_five+"%");
System.out.println("3字单词个数为:"+six+" ,百分比:"+percent_six+"%");
}
}
温馨提示:答案为网友推荐,仅供参考