• Map集合统计字母次数


     Map集合练习:
    "asfefxAAcf34vrfdfse2-2asd--wdd"获取该字符串中,每一个字母出现的次数
    要求打印的结果是:a(2)c(1)...;
    思路:
    对结果分析发现,结果中字母和出现次数之间构成映射关系,而且很多,
    很多就需要存储。能存储映射关系的有数组和Map集合。
    关系中有一方顺序固定么?没有,所以选有Map集合。
    又发现可以作为唯一标识的一方有自然顺序,即字母表的顺序;
    所以选有TreeMap存储。

    集合中最终存储的是以字母为键,以字母出现次数为值的映射关系。
    1.因为操作的是字符,所以先把字符串转化成字符数组。
    2.遍历字符数组,分别以字母为键去Map集合中判断,集合中是否包含该元素,
    如果不包含,则以该字母为键,以1为值,存入Map集合中;
    如果包含,则取出该字母对应的值,加一,再把该字母和新的值存入集合,这样新的值就会覆盖旧的值。
    3.遍历完毕,每个字母对应的值便是其在该字符串中出现的次数,
    在对集合进行打印输出即可。

     1 public class MapTest {
     2 
     3     public static void main(String[] args) {
     4         String str="asfefxAAcf34vrfdfse2-2asd--wdd";
     5         String s=countChar(str);
     6         System.out.println(s);
     7 
     8     }
     9 //定义实现统计字母出现次数的静态方法
    10     public  static String countChar(String str) {
    11         char[] chs=str.toCharArray();
    12         Map<Character,Integer> tm=new TreeMap<Character,Integer>();
    13         for (int i = 0; i < chs.length; i++) {
    14             //只统计字母出现次数,不统计其他字符
    15             if(!(chs[i]>='a' && chs[i]<='z'|| chs[i]>='A' && chs[i]<='Z'))
    16                 continue;
    17             int count=1;
    18             Integer value=tm.get(chs[i]);
    19             if(value!=null)
    20                 count+=value;
    21             tm.put(chs[i], count);
    22         
    23         }
    24         return printMap(tm);
    25     }
    26   //定义按规格打印集合的方法
    27     private static String printMap(Map<Character, Integer> tm) {
    28         StringBuilder sb=new StringBuilder();
    29         Iterator<Character> it=tm.keySet().iterator();
    30         while(it.hasNext())
    31         {
    32             Character key=it.next();
    33             Integer value=tm.get(key);
    34             sb.append(key+"("+value+")  ");
    35         }
    36         return sb.toString();
    37     }
    38 }
  • 相关阅读:
    《AngularJS》5个实例详解Directive(指令)机制
    angularjs入门学习【指令篇】
    --@angularJS--综合小实例1
    --@angularJS--angular与BootStrap3的应用
    --@angularJS--ng-show应用
    --@angularJS--浅谈class与Ng-Class的应用
    --@angularJS--路由插件UI-Router
    --@angularJS--路由、模块、依赖注入
    Bootstrap兼容IE8
    ANGULAR JS PROMISE使用
  • 原文地址:https://www.cnblogs.com/wsw-tcsygrwfqd/p/6419072.html
Copyright © 2020-2023  润新知