碰到的面试题:统计字符串中字母、数字、空格和其他字符的个数
解答如下:
public class Test {
public static void main(String[] args) {
int count1 = 0;//字母的个数
int count2 = 0; //数字的个数
int count3 = 0; //空格的个数
int count4 = 0; //其他字符的个数
String str = "abc123123 , !@#";
char[] ch = str.toCharArray();
for(int i = 0; i < ch.length; i++) {
if(Character.isLetter(ch[i])) {
count1++;
} else if(Character.isDigit(ch[i])) {
count2++;
} else if(Character.isSpaceChar(ch[i])) {
count3++;
} else {
count4++;
}
}
System.out.println("字母的个数:" + count1);
System.out.println("数字的个数:" + count2);
System.out.println("空格的个数:" + count3);
System.out.println("其他字符的个数:" + count4);
}
}