1.问题重述
题目:输入一行字符,分别统计出其英文字母、空格、数字和其它字符的个数。
2.解析
2.1如何判断字符的种类?
对比每一个数值在ASCII码的范围,就可以确定它符号的类别;
char字符ASCII码的范围:
- 数字0到9: 48~57
- 字母A到Z:65到90 a到z:97到122
- 空格是32
2.2如何遍历字符串?
使用for循环对字符串集合Array[]逐个遍历:
for (int i = 0; i < Array.length; i++) {// 遍历字符串
……
}
3.解决问题
代码如下:
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
int num = 0;
int letter = 0;
int space = 0;
int other = 0;
System.out.println("请输入一串字符串:");
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
char[] Array = string.toCharArray();
for (int i = 0; i < Array.length; i++) {// 遍历字符串
if (Array[i] >= 48 && Array[i] <= 57) {// 字符是数字
num++;
} else if ((Array[i] >= 65 && Array[i] <= 90) || (Array[i] >= 97 && Array[i] <= 122)) {// 字符是字母
letter++;
} else if (Array[i] == 32) {// 字符是空格
space++;
} else {// 字符是其他
other++;
}
}
System.out.println("数字:" + num + "个,字母:" + letter + "个,空格:" + space + "个,其他:" + other + "个");
scanner.close();
}
}