① 利用 length()方法获得长度;
② 利用 charAt() 方法访问字符串的第几位;
③ 利用 Character 类的方法来判断是什么;
/*输入一行字符,统计其中字母、数字、空格和其他字符的个数.*/
import java.util.Scanner;
public class CountChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str;
str = sc.nextLine();
int chars,num,space,other; //分别表示字母、数字、空格和其他字符的个数
int ch; //字符串中的一个字符
chars=num=space=other=0;
//统计各类字符的个数
int len = str.length();
for(int i=0;i<len;i++){
if(Character.isLetter(str.charAt(i))){ //判断是不是字母
chars++;
}else if(Character.isDigit(str.charAt(i))){ //判断是不是数字
num++;
}else if(Character.isWhitespace(str.charAt(i))){ //判断是不是空格
space++;
}else{
other++;
}
}
//输出结果
System.out.printf("字母%d数字%d空格%d其他%d\n", chars,num,space,other);
}
}
关于 【Java中的Character类】的进一步讲解;