利用键盘录入字符串,统计该字符串中各个字符的数量

用户输入字符串"Ifyou-wanttochange-your_fate_I_thinkyoumustcome-to-the-dark-horse-to-learn-java"
程序输出结果:
-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)
j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
使用map<Character,Integer>集合实现

public static void main(String[] args) {

/*
  三、分析以下需求,并用代码实现
   1.利用键盘录入,输入一个字符串
   2.统计该字符串中各个字符的数量(提示:字符不用排序)
   3.如:
    用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
    程序输出结果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
*/
   Scanner scanner=new Scanner(System.in);
    System.out.println("请输入字符串");
    String input = scanner.nextLine();
    char[] chars = input.toCharArray();
    //将输入的字符串转化为char类型数组
    Map<Character, Integer> map = new HashMap<>();

    //当前遍历的char数组索引,用于记录每一个元素
    int index = 0;
    //记录char数组找到每个字符出现的次数
    int time = 0;

    //遍历完char数组所有元素
    while (index<chars.length){
        //如果map中没有这个字符
        if (!map.containsKey(index)){
            //就遍历char数组,看此字符出现多少次
            for (int i = 0; i < chars.length; i++) {
                if (chars[index]==chars[i]) {
                    time++;
                }
            }
            //遍历完就把此字符和出现次数添加入map集合
            map.put(chars[index],time);
            index++;
            //添加完成后time置为0,次数清零
            time=0;
        }
    }

    //找到所有的字符集合
    Set<Character> characters = map.keySet();
    //遍历字符集合
    for (Character character : characters) {
        //通过字符找到出现的次数
        Integer integer = map.get(character);
        System.out.print(character+"("+integer+") ");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值