Java 核心技术十二点大学@IT·互联网

题目7:统计字符串中的各种字符的个数

2017-02-12  本文已影响270人  Hughman

题目:

输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

程序分析:

利用while语句,条件为输入的字符不为'\n'
使用正则表达式:
大小写英文字母:[a-zA-Z]
数字:[0-9]
汉字:[\u4E00-\u9FA5]
空格:\s

程序代码:

package com.ljy.tencent;
import java.util.Scanner;
/**
 * 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
 * 程序分析:利用while语句,条件为输入的字符不为'\n'.
 * 使用正则表达式:
 * 大小写英文字母:[a-zA-Z]
 * 数字:[0-9]
 * 汉字:[\u4E00-\u9FA5]
 * 空格:\\s

 * @author liaojianya
 * 2016年10月3日
 */
public class NumberOfChar
{
    public static void main(String[] args)
    {
        System.out.println("请输入一串字符: ");
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        System.out.println("各种字符个数统计如下:");
        count(str);
        input.close();
    }

    public static void count(String str)
    {
        int countLetter = 0;
        int countNumber = 0;
        int countCharacter = 0;
        int countBlankSpace = 0;
        int countOther = 0;

        String E1 = "[a-zA-Z]";
        String E2 = "[0-9]";
        String E3 = "[\u4E00-\u9FA5]";
        String E4 = "\\s";
        //将字符串转换为字符数组
        char[] char_array = str.toCharArray();
        String[] string_array = new String[char_array.length];
        //因为有汉字所以只能将其转换为字符串数组来处理
        for(int i = 0; i < char_array.length; i++)
        {
            string_array[i] = String.valueOf(char_array[i]);
        }
        //遍历字符串数组中的元素
        for(String s : string_array)
        {
            //public boolean matches(String regex),
            //其中regen就是正则表达式到这个字符串进行匹配
            if(s.matches(E1))
            {
                countLetter++;
            }
            else if(s.matches(E2))
            {
                countNumber++;
            }
            else if(s.matches(E3))
            {
                countCharacter++;
            }
            else if(s.matches(E4))
            {
                countBlankSpace++;
            }
            else
            {
                countOther++;
            }
        }
        System.out.println("输入字母的个数为:" + countLetter);
        System.out.println("输入数字的个数为:" + countNumber);
        System.out.println("输入汉字的个数为:" + countCharacter);
        System.out.println("输入空格的个数为:" + countBlankSpace);
        System.out.println("输入其它字符的个数为:" + countOther);
    }

}

结果输出:

请输入一串字符:
h你e l好lo 55 、 \\ ?
各种字符个数统计如下:
输入字母的个数为:5
输入数字的个数为:2
输入汉字的个数为:2
输入空格的个数为:4
输入其它字符的个数为:4
上一篇 下一篇

猜你喜欢

热点阅读