思路
1、把字符串转成字符数组
2、遍历字符数组
3、判断每个字符
字符串
String str = "a b cA B CD<>?</";
转成字符数组
char[] chars = str.toCharArray();
定义四个int类型的计数器
//统计a-z的个数
int azCount = 0;
//统计A-Z的个数
int AZCount = 0;
//统计其他字符的个数
int charCount = 0;
//统计空格的个数
int empty = 0;
遍历字符数组并判断
for (char aChar : chars) {
if ('a' <= aChar && aChar <= 'z'){
azCount++;
}else if ('A' <= aChar && aChar <= 'Z'){
AZCount++;
}else if (aChar == ' '){
empty++;
}else {
charCount++;
}
}
输出
String str = "a b cA B CD<>?</";
System.out.println("a-z:"+azCount);
System.out.println("A-Z:"+AZCount);
System.out.println("空格:"+empty);
System.out.println("其他字符:"+charCount);
a-z:3
A-Z:4
空格:4
其他字符:5
源代码
public class Test {
public static void main(String[] args) {
String str = "a b cA B CD<>?</";
int azCount = 0;
int AZCount = 0;
int charCount = 0;
int empty = 0;
char[] chars = str.toCharArray();
for (char aChar : chars) {
if ('a' <= aChar && aChar <= 'z'){
azCount++;
}else if ('A' <= aChar && aChar <= 'Z'){
AZCount++;
}else if (aChar == ' '){
empty++;
}else {
charCount++;
}
}
System.out.println("a-z:"+azCount);
System.out.println("A-Z:"+AZCount);
System.out.println("空格:"+empty);
System.out.println("其他字符:"+charCount);
}
}