【算法练习】(5)统计字符

题目描述

统计一个给定字符串中指定的字符出现的次数。

输入描述:

测试输入包含若干测试用例,每个测试用例包含2行,第1行为一个长度不超过5的字符串,第2行为一个长度不超过80的字符串。注意这里的字符串包含空格,即空格也可能是要求被统计的字符之一。当读到'#'时输入结束,相应的结果不要输出。

输出描述:

对每个测试用例,统计第1行中字符串的每个字符在第2行字符串中出现的次数,按如下格式输出:
c0 n0
c1 n1
c2 n2
... 
其中ci是第1行中第i个字符,ni是ci出现的次数。

示例1
输入

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 <cstdio>
using namespace std;
int showTimes(char c,string s){
    int t=0;
    for(int i=0;i<s.length();i++){
        if(c==s[i])t++;
    }
    return t;
}
int main(){
    char s1[6],s2[81];
    while(gets(s1)){
        if(s1[0]=='#') break;
        gets(s2);
        for(int i=0;s1[i]!='\0';i++){
            cout<<s1[i]<<" "<<showTimes(s1[i], s2)<<endl;
        }
    }
    return 0;
}
发布了138 篇原创文章 · 获赞 168 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/qq_24734285/article/details/79422098