Java统计字符串中每个字符(单词)个数

来源:互联网 发布:投资网络销售好做吗 编辑:程序博客网 时间:2024/05/22 03:39

一、统计一串字符串中每个字符的个数:

package mycompare;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class arrcompare {public static void main(String args[]) throws Exception {String content = "中国aadf的111萨bbb菲的zz萨菲";HashMap map = new HashMap();for(int i=0;i<content.length();i++){char c=content.charAt(i);Object object=map.get(c);//获取键值if (object==null) {map.put(c, 1);}else {int k=(int)map.get(c);map.replace(c, k, ++k);}}Iterator iterator=map.entrySet().iterator();while(iterator.hasNext()){Map.Entry entry=(Map.Entry)iterator.next();System.out.println(entry.getKey()+":"+entry.getValue());}}}

输出:

a:2
1:3
b:3
菲:2
d:1
的:2
f:1
萨:2
z:2
中:1
国:1



二、统计字符串中每个单词的个数:

package mycompare;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.StringTokenizer;public class arrcompare {public static void main(String args[]) throws Exception {String content = "Hello I am Chinese I come from China";Map map=new HashMap();StringTokenizer tokenizer=new StringTokenizer(content);while(tokenizer.hasMoreTokens()){String string=tokenizer.nextToken();if (map.containsKey(string)) {int k=(int)map.get(string);map.replace(string, k, ++k);}else {map.put(string, 1);}}Iterator iterator=map.entrySet().iterator();while(iterator.hasNext()){Map.Entry entry=(Map.Entry)iterator.next();System.out.println(entry.getKey()+":"+entry.getValue());}}}

输出:

come:1
Hello:1
from:1
China:1
I:2
Chinese:1
am:1

0 0