用c++写一个函数用来统计字符串中各字母出现的次数,示例: 输入:X2Y3XZ,输出:X3Y3Z1; 输入:Z3X(XY)2,输出:X3Y2Z3; 输入:Z4(Y2(XZ2)3)2X2,输出:X8Y4Z16;
时间: 2024-04-29 20:23:51 浏览: 99
C语言编程-编写一个函数,该函数可以统计一个长度为2的字符串在另一个字符串中出现的次数;
5星 · 资源好评率100%
```
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
void count(char *str, int *cnt) {
int len = strlen(str);
for (int i = 0; i < len;) {
if (str[i] >= 'A' && str[i] <= 'Z') {
int j = i + 1;
while (j < len && str[j] >= '0' && str[j] <= '9') {
j++;
}
int num = 0;
for (int k = i + 1; k < j; k++) {
num = num * 10 + str[k] - '0';
}
cnt[str[i] - 'A'] += num;
i = j;
} else if (str[i] == '(') {
int j = i + 1, cnt2[26] = {0};
while (str[j] != ')') {
count(str + j, cnt2);
int k = j + 1;
while (k < len && str[k] >= '0' && str[k] <= '9') {
k++;
}
int num = 0;
for (int l = j; l < k; l++) {
num = num * 10 + str[l] - '0';
}
for (int l = 0; l < 26; l++) {
cnt[l] += cnt2[l] * num;
}
j = k;
}
i = j + 1;
} else {
i++;
}
}
}
int main() {
char str[MAX_LEN];
int cnt[26] = {0};
scanf("%s", str);
count(str, cnt);
for (int i = 0; i < 26; i++) {
if (cnt[i] > 0) {
printf("%c%d", i + 'A', cnt[i]);
}
}
printf("\n");
return 0;
}
```
阅读全文