当前位置: 代码迷 >> Eclipse >> 如何统计一段话中不相同的单词的个数
  详细解决方案

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

热度:41   发布时间:2016-04-23 12:26:27.0
怎么统计一段话中不相同的单词的个数
比如 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());
}
}
  相关解决方案