- import java.util.*;
- class Count
- {
- public Map countStr(String str)
- {
- Map<String,Integer> map = new HashMap<String,Integer>();
- String temp = "";
- for (int i=0;i<str.length();i++)
- {
- temp = str.substring(i,i+1);
- if(map.size()==0)
- {
- map.put(temp,1);//map集合中没数据,添加第一个进去。
- }
- else
- {
- if(map.get(temp)==null)
- {
- map.put(temp,1);//map集合没有,将其加入
- }
- else
- {
- int n = map.get(temp);
- int m = n+1;
- map.put(temp,m);
- }
- }
- }
- return map;
- }
- public static void main(String[] args)
- {
- Count count = new Count();
- Map map = count.countStr("rehtbwegrtrewfwxf");
- //迭代输出
- Set set = map.keySet();
- Iterator it = set.iterator();
- while(it.hasNext())
- {
- String key = (String)it.next();
- int number = (Integer)map.get(key);
- System.out.println(key+"出现:"+number+"次。");
- }
- }
- }
复制代码 |