比如 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());
}
}