输入一行字符,分别统计出其英文字母、空格、数字和其它字符的个数。
做这道题的方法不止一个,在这里,我用的方法是:将字符串转换为字符数组,然后对字符数组进行遍历统计。
有其他的方法欢迎交流!
代码:
import java.util.Scanner;
public class 统计 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("请输入字符:");
String s=sc.nextLine();//将一行字符转化为字符串
sc.close();
count(s);
}
private static void count(String s){
String a="[\u4e00-\u9fa5]";//汉字
String b="[a-zA-Z]";
String c="[0-9]";
String d="\\s";//空格
int countChinese=0;
int countLetter=0;
int countNumber=0;
int conutSpace=0;
int countOther=0;
char[] array_Char=s.toCharArray();//将字符串转换为字符数组
String[] array_String=new String[array_Char.length];//汉字只能作为字符串处理
for(int i=0;i<array_Char.length;i++)
array_String[i]=String.valueOf(array_Char[i]);
//遍历字符串数组中的元素
for(String s1:array_String) {
if (s1.matches(a))
countChinese++;
else if (s1.matches(b))
countLetter++;
else if (s1.matches(c))
countNumber++;
else if (s1.matches(c))
conutSpace++;
else if(s1.matches(d))
conutSpace++;
else
countOther++;
}
System.out.println("输入的汉字个数:"+countChinese);
System.out.println("输入的字母个数:"+countLetter);
System.out.println("输入的数字个数:"+countNumber);
System.out.println("输入的空格个数:"+conutSpace);
System.out.println("输入的其它字符个数:"+countOther);
}
}