黑马程序员技术交流社区

标题: 每天一道小面试题 [打印本页]

作者: 0.Ergou.0    时间: 2016-6-3 23:24
标题: 每天一道小面试题
需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数,其他字符出现的次数。
        * ABCDEabcd123456!@#$%^

作者: likonglin110    时间: 2016-6-3 23:31
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)+")");
                }
        }
作者: 18611643318    时间: 2016-6-4 22:57
  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. }
复制代码
思路能简单一些.

作者: 0.Ergou.0    时间: 2016-6-5 00:05
很不错 都可以的




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2