本题要求编写一个函数,统计由数字字符组成的字符串中,各数字字符出现次数的最大值。在主函数中定义并初始化字符串,调用函数输出结果。要求自定义函数使用指针作为形参。例如,字符串为“110”,输出结果为2。
时间: 2024-02-28 21:56:53 浏览: 21
好的,根据您的要求,我已经明白您的问题了。
以下是解决问题的 C++ 代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int maxNumCount(char* str);
int main() {
char str[] = "110";
int maxCount = maxNumCount(str);
cout << "最大出现次数为:" << maxCount << endl;
return 0;
}
int maxNumCount(char* str) {
int count[10] = {0}; // 数字字符出现次数的计数器
int len = strlen(str);
int max = 0; // 出现次数最大值
for (int i = 0; i < len; i++) {
if (isdigit(str[i])) {
count[str[i] - '0']++; // 统计数字字符出现次数
if (count[str[i] - '0'] > max) {
max = count[str[i] - '0']; // 更新出现次数最大值
}
}
}
return max;
}
```
该函数的思路是:遍历字符串中的每个字符,如果该字符是数字字符,则将该数字字符出现次数加 1,同时更新出现次数最大值。最后返回出现次数最大值。
注意:本题中要求使用指针作为函数形参,因此在函数定义中,参数应该改为 `int maxNumCount(char* str)`。