java字串的遍曆以及字串中各類字元的統計

來源:互聯網
上載者:User

標籤:amp   sys   class   else   多少   main   out   次數   sum   

1、需求:擷取字串中的每一個字元

     分析:
      A:如何能夠拿到每一個字元呢?
           char charAt(int index)
      B:我怎麼知道字元到底有多少個呢?
           int length()

public class StringTest {    public static void main(String[] args) {        // 定義字串        String s = "helloworld";for (int x = 0; x < s.length(); x++) {            // char ch = s.charAt(x);            // System.out.println(ch);            // 僅僅是輸出,我就直接輸出了            System.out.println(s.charAt(x));        }    }}

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:輸出

public class StringTest3 {    public static void main(String[] args) {        //定義一個字串        String s = "Person1314Study";                 //定義三個統計變數        int bignum = 0;        int smallnum = 0;        int numbernum = 0;                //遍曆字串,得到每一個字元。        for(int x=0;x<s.length();x++){            char ch = s.charAt(x);                     //判斷該字元到底是屬於那種類型的            if(ch>=‘A‘ && ch<=‘Z‘){                bignum++;            }            else if(ch>=‘a‘ && ch<=‘z‘){                smallnum++;            }            else if(ch>=‘0‘ && ch<=‘9‘){                numbernum++;            }        }        //輸出結果。        System.out.println("含有"+bignum+"個大寫字母");        System.out.println("含有"+smallnum+"個小寫字母");        System.out.println("含有"+numbernum+"個數字");            }}

 

java字串的遍曆以及字串中各類字元的統計

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.