java 统计字符串中每个字母有多少个

来源:互联网 发布:交警网络执法直播流程 编辑:程序博客网 时间:2024/05/12 12:13

先把字符串转换成字符数组,然后对每个字母,或者数字 每次遍历数组一个个统计就行了。

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个




阅读全文
0 0
原创粉丝点击