jobdu1021字符统计


问题

看下面的问题: [ jobdu-1021]

题目描述:
题目描述:
统计一个给定字符串中指定的字符出现的次数。
输入:
测试输入包含若干测试用例,每个测试用例包含2行,第1行为一个长度不超过5的字符串,第2行为一个长度不超过80的字符串。注意这里的字符串包含空格,即空格也可能是要求被统计的字符之一。当读到’#’时输入结束,相应的结果不要输出。
输出:
对每个测试用例,统计第1行中字符串的每个字符在第2行字符串中出现的次数,按如下格式输出:
c0 n0
c1 n1
c2 n2

其中ci是第1行中第i个字符,ni是ci出现的次数。
样例输入:
I
THIS IS A TEST
i ng
this is a long test string
#
样例输出:
I 2
i 3
5
n 2
g 2

思路

基本题,思路并不难。
将第一个字符串中字符加入集合,
枚举第二个字符串中字符,如果集合中存在相应的元素。那么对应元素次数增加。

代码

#include <iostream>
#include <string>
#include <cstring>
#include <set>
const int maxn = 128;

int counter[maxn];

int main()
{
    std::string pat;
    std::string txt;
    while( std::getline(std::cin, pat) )
    {
        if(1 == pat.size() && '#' == pat[0])
           break;
        std::getline(std::cin, txt);

        std::memset(counter, 0, sizeof(counter));
        int pat_sz = pat.size();
        int txt_sz = txt.size();
        std::set<char> set_exist;

        for( int i = 0; i < pat_sz; ++i )
        {
            set_exist.insert(pat[i]);
        }
        for( int i = 0; i < txt_sz; ++i )
        {
            if( set_exist.find(txt[i]) != set_exist.end() )
                ++counter[(int)(txt[i])];
        }
        for( int i = 0; i < pat_sz; ++i )
        {
            std::cout << pat[i] << " " << counter[(int)(pat[i])] ;
            std::cout << std::endl;
        }

    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值