本帖最后由 余明辉 于 2012-8-5 02:11 编辑
代码中用的那一大串英文,是把2楼的那段话,用google翻译了一下,呵呵。。
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountEng {
public static void main(String[] args) {
String str = "The first stream to read the article in English, " +
"and then to the non-alphanumeric delimiter to split each word, " +
"comparing a single character to determine whether different words, " +
"will read out the word into a special string, use regular expressionsSearch this " +
"special string to determine whether stored in different, " +
"another set of different words the number of counter";
HashMap<String,Integer> map = new HashMap<String,Integer>();
String reg = "\\b(\\w)+\\b";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
int num = 0;
while(m.find()) {
String s = m.group();
if(map.get(s) == null) {
num = 1;
} else {
num++;
}
map.put(s, num);
}
for(Map.Entry<String, Integer> i : map.entrySet()) {
System.out.println(i);
}
}
}
主要就是通过正则去匹配,然后存到map中去,将单词作为key,出现的次数作为value。
这个是我能想出的唯一一个最快的做法了。高手来指点下 |