1、代码如下
public static void main(String[] args) {
String str = "";
int numNum = 0;
int capitalNum = 0;
int lowerCaseNum = 0;
int otherNum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("请输入一串字符:");
str = sc.next();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
capitalNum++;
} else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
numNum++;
} else if (str.charAt(i) >= 'a' && str.charAt(i) < 'z') {
lowerCaseNum++;
} else {
otherNum++;
}
}
System.out.println("大写字母" + capitalNum + "个。");
System.out.println("小写字母" + lowerCaseNum + "个。");
System.out.println("数字" + numNum + "个。");
System.out.println("其他字符" + otherNum + "个。");
}
2、运行效果如图
public class StringCounts {
public static void main(String[] args) {
String strs = "32932sdhkDKjklIO90Fjhd984KLK43h3h.,d%k$%k23ko4GljSRjidfD&5-(0*/-df";
char[] strChars = strs.toCharArray();
int numCounts = 0;//数字统计
int uppCounts = 0;//大写字母统计
int lowCounts = 0;//小字字母统计
int othCounts = 0;//其他字符统计
for (int i = 0; i < strChars.length; i++) {
char c = strChars[i];
if(c>=48 && c<=57){
numCounts++;
}else if(c>=65 && c<=90){
uppCounts++;
}else if(c>=97 && c<=122){
lowCounts++;
}else{
othCounts++;
}
}
System.out.println("数字:" + numCounts + " 个");
System.out.println("大写字母:" + uppCounts + " 个");
System.out.println("小字字母:" + lowCounts + " 个");
System.out.println("其他字符:" + othCounts + " 个");
}
}