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

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

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个




  • 12
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值