• 统计字符出现次数(区分大小写和不区分大小写两种方式)


    package com.st.train;

    import java.util.Arrays;
    import java.util.Scanner;

    //1.区分大小写
    public class StatisticalCharacters2 {
    /**
    * 题目:输入一行字符,统计各个字符(汉字、字母、数字、空格、特殊符号)
    * 出现的个数
    */
    public static void main(String[] args) {
    try (Scanner input = new Scanner(System.in)) {
    System.out.println(“请输入一行字符:”);
    String s=input.nextLine();
    char[] arr = s.toCharArray();
    System.out.println(Arrays.toString(arr));
    for(int i = 0 ; i < arr.length; i++) {
    int count = 0;
    //限制统计过的字符不在统计第二遍
    if (arr[i] != 0 ) {
    char c=arr[i];
    for(int j = 0 ; j < arr.length ; j++) {
    if(c == arr[j]) {
    count++;
    //将之前出现并统计过的字符赋值为0
    arr[j] = 0;
    }
    }
    System.out.println(c+“共有”+count+“个”);
    }
    }
    }
    }
    }

    //2.不区分大小写
    public static void main(String args[]) {
    Scanner in=new Scanner(System.in);

        String str=in.nextLine();
        TreeMap t=new TreeMap<>();
        char x;
    
        for(int i=0;i='a'&&x<='z')||(x>='A'&&x<='Z')) {
                if(x>='a'&& x<='z') {
                    x=Character.toUpperCase(x);
                }
                if(t.containsKey(x)) {
                    t.put(x, t.get(x)+1);
                }else {
                    t.put(x, 1);
                }
            }
        }
    
        Set s=t.keySet();//得到键的集合
        for(char c:s) {//增强for循环
            System.out.println("("+c+")"+"Num="+t.get(c));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    Java学习笔记3.10.4 异常处理 - throw关键字
    MySql事务
    Netty的零拷贝(Zero-Copy)
    乐鑫的ESP32-S3芯片的LE能实现beacon功能吗?
    分享项目管理软件排行榜!
    win10正确配置tensorRT环境
    KVM动态在线迁移实操笔录
    Web3 过冬 有哪些能超越周期的落地产品?
    Tomcat中GET和POST请求时乱码解决
    知识蒸馏学习
  • 原文地址:https://blog.csdn.net/weixin_45591617/article/details/126600514