首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Eclipse开发 >

如何统计一段话中不相同的单词的个数

2012-09-07 
怎么统计一段话中不相同的单词的个数比如 String str“The best a,kind of。frienda is;the kind you can s

怎么统计一段话中不相同的单词的个数
比如 String str=“The best a,kind of。friend a is;the kind you can sit on a porch swing with,”;
怎么输出 不相同单词的个数

[解决办法]

Java code
package sh.pl;import java.util.HashMap;import java.util.Map;public class CountWord {    public static void main(String[] args) {        String str = "The best a,kind of. friend a is;the kind you can sit on a porch swing with,";        Map<String, Integer> tm = new HashMap<String, Integer>();        String[] words = str.split("[\\s\\.,;'\"]");                for (final String s : words) {            if (!s.isEmpty()) {                if (!tm.containsKey(s)) {                    tm.put(s, 1);                } else {                    tm.put(s, tm.get(s).intValue() + 1);                }                            }        }        for (Map.Entry<String, Integer> entry : tm.entrySet()) {            System.out.println(entry.getKey() + ": " + entry.getValue());        }    }}
[解决办法]
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Temp {

public static void main(String[] args) {
String str = "The best a,kind of。friend a is;the kind you can sit on a porch swing with,";
String[] arr = str.split("[\\W]");
Set set = new HashSet(Arrays.asList(arr));
System.out.println("不相同单词的个数:" + set.size());
}
}

热点排行