博客
关于我
输入一串字符串看每一个字符的数量
阅读量:653 次
发布时间:2019-03-15

本文共 1052 字,大约阅读时间需要 3 分钟。

计算一个字符串每个字符出现的个数

  • 分析:

  • 1.使用Scanner获取用户输入的字符串

  • 2.创建Map集合,key是字符串中的字符,value是字符的个数

  • 3.遍历字符串,获取每一个字符

  • 4.使用获取得到的字符,去Map集合判断是否存在

  • key存在:

  • 通过字符(key),获取Value(字符个数)

  • value++;

  • put(key.value)把新的value存储到Map集合中

  • key不存在

  • Put(key,1)

  • 5.遍历Map集合,输出结果

    代码:

    public class Maptest {public static void main(String[] args) {  //输入字符串  Scanner sc=new Scanner(System.in);  System.out.println("请输入字符串");  String abc=sc.next();  //存储到Map中  HashMap
    map=new HashMap<>(); //是用for循环增加value值 for (char c:abc.toCharArray() ) { if (map.containsKey(c)) { Integer value = map.get(c); value++; map.put(c,value); } else { map.put(c,1); } } //使用Enteryset方法 Set
    > entries = map.entrySet(); for (Map.Entry
    entry:entries ) { //打印输出各个字符的数量 System.out.println("字符"+entry.getKey()+"有"+entry.getValue()+"个"); } }}

    显示效果

    请输入字符串

    sdkafgjhlakjflf34-=
    字符a有2个
    字符d有1个
    字符f有3个
    字符g有1个
    字符h有1个
    字符j有2个
    字符k有2个
    字符l有2个
    字符-有1个
    字符s有1个
    字符3有1个
    字符4有1个
    字符=有1个

转载地址:http://aljmz.baihongyu.com/

你可能感兴趣的文章
mysql -存储过程
查看>>
mysql /*! 50100 ... */ 条件编译
查看>>
mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>