自己写的两种方式,直接上代码:
- <p>/*
- * 统计字符串中大写、小写、数字出现的次数
- */
- public class Demo3 {
- public static void main(String[] args) {
- //给定的字符串
- String s = "GHJKasdf1234";
-
- method1(s);
- System.out.println("----------");
- method2(s);</p><p> }</p><p> // 方法1
- public static void method1(String s) {
- int upper = 0;
- int lower = 0;
- int digit = 0;
- char[] arr = s.toCharArray();
- for (int i = 0; i < arr.length; i++) {
- if (arr[i] >= 'A' && arr[i] <= 'Z') {
- upper++;
- } else if (arr[i] >= 'a' && arr[i] <= 'z') {
- lower++;
- } else if (arr[i] >= '0' && arr[i] <= '9') {
- digit++;
- }
- }
- System.out.println("大写字母出现的次数:" + upper);
- System.out.println("小写字母出现的次数:" + lower);
- System.out.println("数字出现的次数:" + digit);
- }</p><p> // 方法2
- public static void method2(String s) {
- int upper = 0;
- int lower = 0;
- int digit = 0;
- char[] arr = s.toCharArray();
- for (int i = 0; i < arr.length; i++) {
- if (Character.isUpperCase(arr[i])) {
- upper++;
- } else if (Character.isLowerCase(arr[i])) {
- lower++;
- } else if (Character.isDigit(arr[i])) {
- digit++;
- }
- }
- System.out.println("大写字母出现的次数:" + upper);
- System.out.println("小写字母出现的次数:" + lower);
- System.out.println("数字出现的次数:" + digit);
- }
- }
- </p><p> </p>
复制代码
|
|