c++用类的封装实现x~y中0~9数字出现次数的统计
时间: 2023-06-01 13:04:50 浏览: 59
好的,这是一个合适的问题。我可以通过以下代码实现:
```
#include <iostream>
#include <cstring>
using namespace std;
class CountDigits {
public:
int count[10];
CountDigits(string str) {
memset(count, 0, sizeof(count));
for (int i = 0; i < str.length(); i++) {
if (str[i] >= '0' && str[i] <= '9') {
count[str[i]-'0']++;
}
}
}
void display() {
for (int i = 0; i < 10; i++) {
cout << i << "出现的次数:" << count[i] << endl;
}
}
};
int main() {
string str = "x23y456z7890";
CountDigits obj(str);
obj.display();
return 0;
}
```
在main函数中,我们创建了一个CountDigits对象,并传入了一个带有数字的字符串参数。在CountDigits类中,我们使用count数组统计数字0到9在字符串中出现的次数,然后在display函数中输出结果。
希望这个代码能够满足您的需求,如果您有任何其他问题,请继续提问。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)