题目1021:统计字符

来源:互联网 发布:大智慧 股票数据接口 编辑:程序博客网 时间:2024/05/22 15:21

题目描述:
    统计一个给定字符串中指定的字符出现的次数。
输入:
    测试输入包含若干测试用例,每个测试用例包含2行,第1行为一个长度不超过5的字符串,第2行为一个长度不超过80的字符串。注意这里的字符串包含空格,即空格也可能是要求被统计的字符之一。当读到'#'时输入结束,相应的结果不要输出。
输出:
    对每个测试用例,统计第1行中字符串的每个字符在第2行字符串中出现的次数,按如下格式输出:
    c0 n0
    c1 n1
    c2 n2
    ... 
    其中ci是第1行中第i个字符,ni是ci出现的次数。
样例输入:
ITHIS IS A TESTi ngthis is a long test string#
样例输出:
I 2i 3  5n 2g 2

代码

首先附上C语言版的,字符串处理最好用c++,c比较麻烦

#include<stdio.h>#include<string.h>int main(){char str1[5], str2[80];int i, j, count;while (gets(str1) && strcmp(str1, "#") != 0){gets(str2);for (i = 0; str1[i] != '\0'; i++){count = 0;for (j = 0; str2[j] != '\0'; j++){if (str1[i] == str2[j]){count++;}}printf("%c %d\n", str1[i], count);}}}

C++版本

#include<iostream>  #include<string>  using namespace std;int main(){int i, j,count;string str1, str2;while (getline(cin, str1)){if (str1 == "#")         //C++比较字符串相等直接可以比较return 0;int str1_len = str1.size();getline(cin, str2);for (i = 0; str1[i] != '\0'; i++){count = 0;for (j = 0; str2[j] != '\0'; j++){if (str1[i] == str2[j])count++;}printf("%c %d\n", str1[i], count);}}}


0 0