package cn.shen.first;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/*
* 统计一个字符串中,单词出现的频率 沈碧玲
*/
public class Rate {
public void countWord(String str){
String[] t=str.split("\s+|[,.?!]");//正则表达式,以空格或",.!?"区分单词
Map<String,Integer> wordsMap=new HashMap<String,Integer>();
//增强for循环,输入到集合
for(String word:t){
if(wordsMap.containsKey(word)){
wordsMap.put(word, wordsMap.get(word)+1);
}
else{
wordsMap.put(word, 1);
}
}
Set<String> setKey=wordsMap.keySet();
Iterator<String> itk=setKey.iterator();
//遍历集合
while(itk.hasNext()){
String word=itk.next().toString();
int sum=wordsMap.get(word);
System.out.println("单词 "+word +"出现" +sum+"次");
}
}
}
import org.junit.Test;
public class RateTest {
@Test
public void test() throws IOException{
System.out.println("请输入一个字符串:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
str=br.readLine();
Rate r=new Rate();
r.countWord(str);
}
}