java11-4 字符串的遍历以及字符串中各类字符的统计

1、需求:获取字符串中的每一个字符

     分析:
      A:如何能够拿到每一个字符呢?
           char charAt(int index)
      B:我怎么知道字符到底有多少个呢?
           int length()

 1 public class StringTest {
 2     public static void main(String[] args) {
 3         // 定义字符串
 4         String s = "helloworld";
 5 for (int x = 0; x < s.length(); x++) {
 6             // char ch = s.charAt(x);
 7             // System.out.println(ch);
 8             // 仅仅是输出,我就直接输出了
 9             System.out.println(s.charAt(x));
10         }
11     }
12 }


2、需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)

  举例:
    "Person1314Study"
  分析:
    A:先定义三个变量
        bignum、samllnum、numbersum
    B:进行数组的遍历
        for()、lenght()、charAt()
    C:判断各个字符属于三个变量哪个
        bignum:(ch>='A' && ch<='Z')
        smallnum:(ch>='a' && ch<='z')
        numbersum:(ch>='0' && ch<='9')
    D:输出

 1 public class StringTest3 {
 2 
 3     public static void main(String[] args) {
 4         //定义一个字符串
 5         String s = "Person1314Study";
 6         
 7          //定义三个统计变量
 8         int bignum = 0;
 9         int smallnum = 0;
10         int numbernum = 0;
11         
12         //遍历字符串,得到每一个字符。
13         for(int x=0;x<s.length();x++){
14             char ch = s.charAt(x);
15             
16          //判断该字符到底是属于那种类型的
17             if(ch>='A' && ch<='Z'){
18                 bignum++;
19             }
20             else if(ch>='a' && ch<='z'){
21                 smallnum++;
22             }
23             else if(ch>='0' && ch<='9'){
24                 numbernum++;
25             }
26         }
27         //输出结果。
28         System.out.println("含有"+bignum+"个大写字母");
29         System.out.println("含有"+smallnum+"个小写字母");
30         System.out.println("含有"+numbernum+"个数字");
31         
32 
33     }
34 
35 }




何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5875704.html