计不同字符个数
用户从键盘输入一行字符,编写一个程序,统计并输出中、英文字符、数字、空格和其他字符的个数。
实现代码如下:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test02 {
public static void main(String[] args) {
System.out.println("请输入一段字符:");
Scanner a = new Scanner(System.in);
String b = a.nextLine();
int zw = 0, yw = 0, sz = 0, kg = 0, qt = 0;
int h = b.length();
for (int i = 0; i < h; i++) {
if (b.charAt(i) >= 65 && b.charAt(i) <= 90) {
yw++;
} else if (b.charAt(i) >= 97 && b.charAt(i) <= 122) {
yw++;
} else if (b.charAt(i) == 32) {
kg++;
} else if (b.charAt(i) >= 48 && b.charAt(i) <= 57) {
sz++;
}else {
qt++;
}
}
String zz = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(zz);
Matcher m = p.matcher(b);
while(m.find()){
zw ++;
}
qt = qt - zw;
System.out.println("英文有:" + yw + "个");
System.out.println("中文有:" + zw + "个");
System.out.println("数字有:" + sz + "个");
System.out.println("空格有:" + kg + "个");
System.out.println("其他有:" + qt + "个");
}
}