Java统计字符串中各种字母个数

从标准输入接受一行字符,分别统计该行字符中英文字母、其它字符的个数,并分别输出这些字符。

package doc_01.third;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 模块说明: 输入一行字符统计中英文字母个数,并输出
 * 
 */
public class CountChar {
    private static int count[] = new int[3];
    // private static StringBuffer[] sb = new StringBuffer[3];
    private static StringBuffer chinese = new StringBuffer("中文字母:");
    private static StringBuffer english = new StringBuffer("英文字母:");
    private static StringBuffer other = new StringBuffer("其他字母:");

    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            String inputStr = br.readLine();
            count(inputStr);
            display();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void count(String inputStr) {
        char[] temp = inputStr.toCharArray();
        for (int i = 0; i < temp.length; i++) {
            if (isChinese(temp[i])) {
                chinese.append(temp[i] + " ");
                count[0]++;
                continue;
            }
            if (isEnglish(temp[i])) {
                english.append(temp[i] + " ");
                count[1]++;
                continue;
            }
            other.append(temp[i] + " ");
            count[2]++;
        }
    }

    private static boolean isChinese(char c) {
        Character.UnicodeScript sc = Character.UnicodeScript.of(c);
        if (sc == Character.UnicodeScript.HAN) {
            return true;
        }
        return false;
    }

    private static boolean isEnglish(char c) {
        if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) {
            return true;
        } else {
            return false;
        }
    }

    private static void display() {
        System.out.println("中文字母个数:" + count[0]);
        System.out.println(chinese);
        System.out.println("英文字母个数:" + count[1]);
        System.out.println(english);
        System.out.println("其他字母个数:" + count[2]);
        System.out.println(other);
    }
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值