题解 | 判断各类型字符个数
import java.util.Scanner; public class Main { public static void main(String[] args) { int numbers = 0; int words = 0; int space = 0; int other = 0; Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); //write your code here...... for (int i = str.length() - 1; i >= 0; i--) { char c = str.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { words++; } else if (c >= '0' && c <= '9') { numbers++; } else if (c == ' ') { space++; } else { other++; } } System.out.println("英文字母" + words + "数字" + numbers + "空格" + space + "其他" + other); } }
两种解法
for (int i = str.length() - 1; i >= 0; i--) { char c = str.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { words++; } else if (c >= '0' && c <= '9') { numbers++; } else if (c == ' ') { space++; } else { other++; } }
for(int i=str.length()-1;i>=0;i--){ char c=str.charAt(i); if(Character.isLetter(c)){ words++; }else if(Character.isDigit(c)){ numbers++; }else if(Character.isSpaceChar(c)){ space++; }else{ other++; } }