统计字符(字符串,简单)

统计字符

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5479    Accepted Submission(s): 3418

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

 

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

 

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

 

Sample Input
I THIS IS A TEST i ng this is a long test string #
 

 

Sample Output
I 2 i 3 5 n 2 g 2 注:第2个测试用例中,空格也是被统计的字符之一。
 

 

Source
 

 

Recommend
lcy
 


 1 #include <iostream>
 2 #include <map>
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     char s[6], c;
10     int i;
11     map<char, int> M;
12     while(1)
13     {
14         for(i = 0; scanf("%c", &c) && c != '\n'; i++)
15         {
16             s[i] = c;
17         }
18         s[i] = '\0'; // important!
19         if(!strcmp(s, "#")) break;
20         for(i = 0; s[i] != '\0'; i++)
21             if(!M[s[i]]) M[s[i]] = 1;
22         while(scanf("%c", &c))
23         {
24             if(c == '\n') break;
25             if(M[c]) M[c]++;
26         }
27         for(i = 0; s[i] != '\0'; i++)
28         {
29             printf("%c %d\n", s[i], M[s[i]] - 1);
30         }
31         for(int i = 0; s[i] != '\0'; i++)
32             M[s[i]] = 0;
33     }
34     return 0;
35 }

 

 

posted on 2012-08-27 20:16  铁树银花  阅读(289)  评论(0编辑  收藏  举报

导航