描述
统计一个给定字符串中指定的字符出现的次数。
输入描述:
测试输入包含若干测试用例,每个测试用例包含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 <stdio.h>
#include <string.h>
#define MAX_TARGET_LEN 5 // 目标字符串的最大长度
#define MAX_STR_LEN 80 // 待统计字符串的最大长度
// 统计字符出现的次数
void countCharacters(char target[], char str[]) {
int len1 = strlen(target); // 目标字符串的长度
int len2 = strlen(str); // 待统计字符串的长度
// 遍历目标字符串中的每个字符
for (int i = 0; i < len1; i++) {
char c = target[i]; // 当前目标字符
int count = 0; // 计数器
// 遍历待统计字符串,统计字符出现次数
for (int j = 0; j < len2; j++) {
if (str[j] == c) {
count++;
}
}
// 输出结果
printf("%c %d\n", c, count);
}
}
int main() {
char target[MAX_TARGET_LEN + 1]; // 目标字符串
char str[MAX_STR_LEN + 1]; // 待统计字符串
while (1) {
// 读取目标字符串
if (fgets(target, sizeof(target), stdin) == NULL) {
break;
}
// 去掉目标字符串的换行符
size_t len = strlen(target);
if (len > 0 && target[len - 1] == '\n') {
target[len - 1] = '\0';
}
// 如果目标字符串是 "#",结束程序
if (strcmp(target, "#") == 0) {
break;
}
// 读取待统计字符串
if (fgets(str, sizeof(str), stdin) == NULL) {
break;
}
// 去掉待统计字符串的换行符
len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
}
// 统计并输出结果
countCharacters(target, str);
}
return 0;
}