统计字符串中每个字母出现的次数

给定一个包含各种字符的字符串,打印出其中字母和其出现的次数。

实现原理:

1. 利用正则匹配去除非字母字符。

2. 将字母为键,出现次数为值存入map。

3. 扫描字符串,若字母已存在于map中,值加1.

4. 打印map。

 

    public static void count(String input) 
    { 
//?表示非贪婪匹配,i表示忽略大小写,[^a-z]匹配所有非a-z范围类字符。 String regex
= "(?i)[^a-z]"; String result = input.replaceAll (regex, ""); System.out.println (result); HashMap<String, Integer> map = new HashMap<String, Integer> (); for ( int i = 0; i < result.length (); i++ ) { String one = result.charAt (i) + ""; if (null == map.get (one)) { //新字符,存入map,值为1 map.put (one, 1); } else { //已存在,值加一 map.put (one, map.get (one) + 1); } } System.out.println (map); }

 测试代码:

    public static void main ( String args[] ) {
        String input = "016a 8b9c213d20df0G9E"; 
        CountLetters test= new CountLetters();
        test.countAlphabet(input);
    }

返回结果:

abcddfGE
{f=1, E=1, d=2, G=1, b=1, c=1, a=1}

 

转载于:https://www.cnblogs.com/clarke157/p/6811165.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值