- package com.itheima.test;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- public class FindStringTimes {
- public static void main(String[] args) {
- String str = "黑化肥发黑不发灰,灰化肥发灰不发黑灰";
- //将字符串转换成字符数组
- char[] chs = str.toCharArray();
- //定义一个Map集合,存储数据,键为字符,值为出现次数
- Map<Character, Integer> map = new TreeMap<Character, Integer>();
-
- //遍历数组,
- for (int i = 0; i < chs.length; i++) {
- int count = 1;//定义初始化出现次数
- Integer value = map.get(chs[i]);//获取字符键对应的值
- if (value != null) {//存储时,如果值(出现次数)不为空
- count = value + 1;//则计数器加1次
- }
- map.put(chs[i], count);//将字符键,对应次数存放到集合中
- }
-
- //迭代集合方法1
- Set<Map.Entry<Character, Integer>> entry_Set = map.entrySet();
- Iterator<Map.Entry<Character, Integer>> it = entry_Set.iterator();
- while (it.hasNext()) {
- Map.Entry<Character, Integer> me = it.next();
- Character ch = me.getKey();
- Integer value = me.getValue();
- System.out.println(ch + ":::" + value);
- }
-
- //方法2
- for (Character ch : map.keySet()) {
- Integer value = map.get(ch);
- System.out.println(ch+".."+value);
-
- }
- //方法3
- for(Map.Entry<Character, Integer> me : map.entrySet()){
- Character ch = me.getKey();
- Integer value = me.getValue();
- System.out.println(ch+"=="+value);
- }
- }
- }
复制代码 运行结果
- ,:::1
- 不:::2
- 化:::2
- 发:::4
- 灰:::4
- 肥:::2
- 黑:::3
- ,..1
- 不..2
- 化..2
- 发..4
- 灰..4
- 肥..2
- 黑..3
- ,==1
- 不==2
- 化==2
- 发==4
- 灰==4
- 肥==2
- 黑==3
复制代码
|