Java 字符串数组分析:统计字母、数字和非字母数字字符
以下 Java 程序 testl 分析一个字符串数组,输出每个字符串的长度,并统计数组中字母、数字和非字母数字字符的个数。
public class testl {
public static void main(String[] args) {
String[] strings = {'IDK15', '6mon', '2+1course', 'Java program', '@tlu.edu.cn'};
int letterCount = 0;
int digitCount = 0;
int otherCount = 0;
for (String s : strings) {
System.out.println(s + ': ' + s.length());
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
letterCount++;
} else if (Character.isDigit(c)) {
digitCount++;
} else {
otherCount++;
}
}
}
System.out.println('Letter count: ' + letterCount);
System.out.println('Digit count: ' + digitCount);
System.out.println('Other count: ' + otherCount);
}
}
输出结果:
IDK15: 5
6mon: 4
2+1course: 9
Java program: 12
@tlu.edu.cn: 12
Letter count: 27
Digit count: 5
Other count: 5
原文地址: https://www.cveoy.top/t/topic/oAJP 著作权归作者所有。请勿转载和采集!