题目描述
输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数
输入描述:
输入一行字符串,可以有空格
输出描述:
统计其中英文字符,空格字符,数字字符,其他字符的个数
算法实现:
package com.husweijishi.suanfa;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 统计字符串中的英文、数字、空格和其他字符个数
* @author liyongyong
* 2016年12月1日
*/
public class CountCharacter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String str = scanner.nextLine();
System.out.println(getEnglishCharCount(str));
System.out.println( getBlankCharCount(str));
System.out.println(getNumberCharCount(str));
System.out.println(getOtherCharCount(str));
}
}
private static int getEnglishCharCount(String str) {
int count = 0;
Pattern pattern = Pattern.compile("[a-zA-Z]");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
count++;
}
return count;
}
private static int getBlankCharCount(String str) {
int count = 0;
Pattern pattern = Pattern.compile("\\u0020");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
count++;
}
return count;
}
private static int getNumberCharCount(String str) {
int count = 0;
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
count++;
}
return count;
}
private static int getOtherCharCount(String str) {
int count = 0;
Pattern pattern = Pattern.compile("[^0-9a-zA-Z\\u0020]");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
count++;
}
return count;
}
}