c++输入一个字符串,统计字符
时间: 2023-11-26 15:03:00 浏览: 89
好的,我可以帮你写一个统计字符串字符的程序。你可以使用`getline`函数输入整行字符串,然后使用`length()`函数获取字符串长度,最后遍历字符串并统计字符出现的次数即可。下面是示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s); // 输入整行字符串
int len = s.length(); // 获取字符串长度
int cnt[256] = {0}; // 统计字符出现次数的数组
// 遍历字符串并统计字符出现次数
for (int i = 0; i < len; i++) {
cnt[s[i]]++;
}
// 输出字符及其出现次数
for (int i = 0; i < 256; i++) {
if (cnt[i] > 0) {
cout << static_cast<char>(i) << ": " << cnt[i] << endl;
}
}
return 0;
}
```
请注意,该程序统计字符的范围是 ASCII 码表,因此最多统计 256 种字符。如果需要统计 Unicode 字符,需要使用更加复杂的方法。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)