题解 | #统计字符#
统计字符
https://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5
这里主要考察的还是字符串中单个字符怎么判断是数字还是字母:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); int len = s.length(); // 定义计数器 int c_letter = 0; int c_black = 0; int c_num = 0; int c_other = 0; // 循环遍历这个字符串 for(int i = 0; i < len; i++) { char c = s.charAt(i); if(isLetter(c)) { c_letter ++ ; } else if(c == ' ') { c_black ++ ; } else if(isNum(c)) { c_num ++; } else { c_other ++ ; } } System.out.print(c_letter + "\n" + c_black + "\n" + c_num + "\n" + c_other + "\n"); } // 验证字符是否是数字 public static boolean isNum(char c) { return Character.isDigit(c); } // 验证字符是否是字母 public static boolean isLetter(char c) { boolean c1 = c >= 'A' && c <= 'Z'; boolean c2 = c >= 'a' && c <= 'z'; return c1 || c2; } }