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 }

 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM