统计字母出现次数

这段Java代码实现了一个字符串中字符出现次数的统计功能,包括大写字母(A-Z),小写字母(a-z)和数字(0-9)。通过输入字符串,程序会输出各字符的出现频率,特别地,它在`countTimes`方法中处理了'Firefox can’t establish a connection to the server at localhost:9870.'这个示例。
摘要由CSDN通过智能技术生成
import java.util.Scanner;

public class CountString {
    public static void main(String[] args) {

/*
        Scanner sc = new Scanner(System.in);
        System.out.println("please shuru: ");
        String line = sc.nextLine();
        char[] ch = line.toCharArray();

        int countA = 0;
        int counta = 0;
        int count1 = 0;
        int[] count = new int[61];
        char[] zimu = new char[61];
        for (int i = 0; i < ch.length; i++) {
            for (int j = 0; j < ch.length; j++)
                if (ch[i] == ch[j]) {
                    count[i] += 1;
                    zimu[i] = ch[i];

                }


        }*/

      /*  for(int i=0;i<ch.length;i++){
            if(ch[i]>=97 && ch[i]<=122){
                counta+=1;

            }
            else if(ch[i]>=65 && ch[i] <=90){
                countA+=1;

            }
            else if(ch[i]>=48 && (int)ch[i]<=57){
                count1+=1;

            }
        }*/
       /* for(int i=0;i<ch.length;i++){
            if(ch[i]>='a' && ch[i]<='z'){
                counta+=1;

            }
            else if(ch[i]>='A' && ch[i] <='Z'){
                countA+=1;

            }
            else if(ch[i]>='0' && (int)ch[i]<='9'){
                count1+=1;

            }
        }*/
        /*for (int i = 0; i < ch.length; i++) {
            if (ch[i]=='a'){
                counta+=1;
            }
            else if(ch[i]=='A'){
                countA+=1;
            }
            else if(ch[i]=='1'){
                count1+=1;
            }

        }

        System.out.println("A :" + countA);
        System.out.println("a :" + counta);
        System.out.println("1 :" + count1);*/


        countTimes("Firefox can’t establish a connection to the server at localhost:9870.");
    }

    public static void countTimes(String src) {
        int[] count = new int[52];
        for (char c : src.toCharArray()) {
            int index = c - 'A';
            if (index > 25) {
                index = index - 6;
            }
            if (index < 0 || index > 51) {
                continue;
            }
            count[index] += 1;
        }
        for (int i = 0; i < count.length; i++) {
            if (count[i] == 0) {
                continue;
            }
            if (i > 25) {
                System.out.println(((char) ('a' + i - 26) + "-->" + count[i]));
            } else {
                System.out.println(((char) ('A' + i)) + "-->" + count[i]);
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值