博客
关于我
输入一串字符串看每一个字符的数量
阅读量: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/

你可能感兴趣的文章
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node
查看>>
node exporter完整版
查看>>