public class StringHomework03 {
public static void main(String[] args) {
try {
String s = statisticChar1("123abcABC");
// 数字个数: 3, 大写字母个数: 3, 小写字母个数: 3
System.out.println(s);
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
String s2 = statisticChar2("ABCabc123");
// 数字个数: 3, 大写字母个数: 3, 小写字母个数: 3
System.out.println(s2);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static String statisticChar1(String str) {
if (str == null) {
throw new RuntimeException("字符串不能为空");
}
int numberCount = 0;
int BigCount = 0;
int smallCount = 0;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] >= '0' && chars[i] <= '9') {
numberCount++;
} else if (chars[i] >= 'A' && chars[i] <= 'Z') {
BigCount++;
} else if (chars[i] >= 'a' && chars[i] <= 'z') {
smallCount++;
}
}
return "数字个数: " + numberCount + ", 大写字母个数: " + BigCount + ", 小写字母个数: " + smallCount;
}
public static String statisticChar2(String str) {
if (str == null) {
throw new RuntimeException("字符串不能为空");
}
int numberCount = 0;
int BigCount = 0;
int smallCount = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= '0' && c <= '9') {
numberCount++;
} else if (c >= 'A' && c <= 'Z') {
BigCount++;
} else if (c >= 'a' && c <= 'z') {
smallCount++;
}
}
return "数字个数: " + numberCount + ", 大写字母个数: " + BigCount + ", 小写字母个数: " + smallCount;
}
}