一、思路
通过for循环遍历字符串中的每个字符并判断是否是字母或数字,如果是字母则将字母个数进行加一,若是数字则将数字个数加一。
二、实现代码
public class Test2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("输入一个字符串:");
String a=sc.nextLine();
int anum=0;//字母计数
int num=0;//数字计数
for (int i = 0; i <a.length() ; i++) {
//将遍历到的字符转换成String,并通过matches(String reg)正则匹配,返回false或true
if (Character.toString(a.charAt(i)).matches("[a-zA-Z]"))
anum+=1;
else if (Character.toString(a.charAt(i)).matches("[0-9]"))
num+=1;
}
System.out.println("字母有"+anum+"个,数字有"+num+"个");
}
}
二、实现代码
输入一个字符串:adad45 a12ad a45
字母有8个,数字有6个