读书人

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

发布时间: 2012-09-07 10:38:15 作者: rapoo

怎么统计一段话中不相同的单词的个数
比如 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());
}
}

读书人网 >Eclipse开发

热点推荐