java 統計字串中每個字母有多少個

來源:互聯網
上載者:User

先把字串轉換成字元數組,然後對每個字母,或者數字 每次遍曆數組一個個統計就行了。

package yaxin;public class CountString{public static void main(String[] args){String string="abcedfgaaaabbbccccBBBCCCEEE22334455";char chs[]=string.toCharArray();//轉換成char數組int count=0;System.out.println("字串:"+string+"中小寫字母有:");for(char ch='a';ch<'z';ch++){count=0;//計數器for(int i=0;i<chs.length;i++){if(ch==chs[i])count++;}if(count!=0)System.out.println("字元中"+ch+"有"+count+"個");}System.out.println("字串:"+string+"中大寫字母有:");for(char ch='A';ch<'Z';ch++){count=0;//計數器for(int i=0;i<chs.length;i++){if(ch==chs[i])count++;}if(count!=0)System.out.println("字元中"+ch+"有"+count+"個");}System.out.println("字串:"+string+"中數字有:");for(char ch='0';ch<'9';ch++){count=0;//計數器for(int i=0;i<chs.length;i++){if(ch==chs[i])count++;}if(count!=0)System.out.println("字元中"+ch+"有"+count+"個");}}}
結果:
字串:abcedfgaaaabbbccccBBBCCCEEE22334455中小寫字母有:字元中a有5個字元中b有4個字元中c有5個字元中d有1個字元中e有1個字元中f有1個字元中g有1個字串:abcedfgaaaabbbccccBBBCCCEEE22334455中大寫字母有:字元中B有3個字元中C有3個字元中E有3個字串:abcedfgaaaabbbccccBBBCCCEEE22334455中數字有:字元中2有2個字元中3有2個字元中4有2個字元中5有2個




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.