題目:
輸入一行字符,分別統(tǒng)計出其中英文字母、空格赐俗、數(shù)字和其它字符的個數(shù)。
程序分析:
利用while語句,條件為輸入的字符不為'\n'
使用正則表達式:
大小寫英文字母:[a-zA-Z]
數(shù)字:[0-9]
漢字:[\u4E00-\u9FA5]
空格:\s
程序代碼:
package com.ljy.tencent;
import java.util.Scanner;
/**
* 題目:輸入一行字符弊知,分別統(tǒng)計出其中英文字母阻逮、空格、數(shù)字和其它字符的個數(shù)秩彤。
* 程序分析:利用while語句,條件為輸入的字符不為'\n'.
* 使用正則表達式:
* 大小寫英文字母:[a-zA-Z]
* 數(shù)字:[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("各種字符個數(shù)統(tǒng)計如下:");
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";
//將字符串轉(zhuǎn)換為字符數(shù)組
char[] char_array = str.toCharArray();
String[] string_array = new String[char_array.length];
//因為有漢字所以只能將其轉(zhuǎn)換為字符串?dāng)?shù)組來處理
for(int i = 0; i < char_array.length; i++)
{
string_array[i] = String.valueOf(char_array[i]);
}
//遍歷字符串?dāng)?shù)組中的元素
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("輸入字母的個數(shù)為:" + countLetter);
System.out.println("輸入數(shù)字的個數(shù)為:" + countNumber);
System.out.println("輸入漢字的個數(shù)為:" + countCharacter);
System.out.println("輸入空格的個數(shù)為:" + countBlankSpace);
System.out.println("輸入其它字符的個數(shù)為:" + countOther);
}
}
結(jié)果輸出:
請輸入一串字符:
h你e l好lo 55 叔扼、 \\ ?
各種字符個數(shù)統(tǒng)計如下:
輸入字母的個數(shù)為:5
輸入數(shù)字的個數(shù)為:2
輸入漢字的個數(shù)為:2
輸入空格的個數(shù)為:4
輸入其它字符的個數(shù)為:4