A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 0.Ergou.0 中级黑马   /  2016-6-3 23:24  /  693 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数,其他字符出现的次数。
        * ABCDEabcd123456!@#$%^

3 个回复

倒序浏览
public static void main(String[] args) {
                String a="  * ABCDEabcd123456!@#$%^";
                char[] newChar = a.toCharArray();   //将筛选后的字符串转换成字符数组
        
        //3、建立一个HashMap集合
        TreeMap<Character, Integer> map = new TreeMap<>();
         
        //4、遍历字符数组,将每个字符作为键存入集合中,将字符出现的次数作为值存入集合中
        for (char d : newChar) {
            map.put(d, !map.containsKey(d)? 1 : map.get(d)+1);  //判断集合中是否存在键,不存在,则将该键对应的值设置为1;存在该键,则获取该键对应的值,并加1
        }
        //5、遍历集合输出结果
        for (Character c : map.keySet()) {
                        System.out.print(c+"("+map.get(c)+")");
                }
        }
回复 使用道具 举报
  1. package com.itheima;

  2. /**
  3. * 需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数,其他字符出现的次数。
  4. * ABCDEabcd123456!@#$%^
  5. *
  6. * @author Venus
  7. *
  8. */
  9. public class Test38 {
  10.         public static void main(String[] args) {
  11.                 //定义字符串
  12.                 String str = "ABCDEabcd123456!@#$%^";
  13.                 //定义计数器
  14.                 int big = 0;                        //大写计数器
  15.                 int small = 0;                        //小写计数器
  16.                 int num = 0;                        //数字计数器
  17.                 int other = 0;                        //其他计数器
  18.                
  19.                 for (int i = 0; i < str.length(); i++) {
  20.                         char ch = str.charAt(i);                        //取到每一个字符
  21.                         if(ch >= 'a'&& ch <= 'z'){                        //判断是否在小写a-z,如果在,小写small++
  22.                                 small++;
  23.                         }else if (ch >= 'A'&& ch <= 'Z'){        //判断大写
  24.                                 big++;                                                       
  25.                         }else if (ch >= '0'&& ch <= '9'){        //判断数字
  26.                                 num++;
  27.                         }
  28.                 }
  29.                 other = str.length() - big - small - num;        //其他字符
  30.                 System.out.println("大写:"+big);
  31.                 System.out.println("小写:"+small);
  32.                 System.out.println("数字:"+num);
  33.                 System.out.println("其他:"+other);
  34.         }
  35. }
复制代码
思路能简单一些.
回复 使用道具 举报
很不错 都可以的
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马