字符统计c++
时间: 2023-06-29 14:06:46 浏览: 65
以下是一个简单的 C++ 程序,用于统计字符串中字符的出现次数:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "输入字符串: ";
getline(cin, str);
int count[256] = {0};
for (int i = 0; i < str.length(); i++)
{
count[(int)str[i]]++;
}
for (int i = 0; i < 256; i++)
{
if (count[i])
{
cout << "'" << (char)i << "' 出现 " << count[i] << " 次" << endl;
}
}
return 0;
}
```
该程序首先通过 `getline()` 函数从用户输入中获取一个字符串,然后创建一个整型数组 `count`,初始化为 0。接下来,程序遍历字符串中的每个字符,并使用 ASCII 码将其作为数组 `count` 的下标,递增相应的计数器。最后,程序遍历整个计数器数组并输出每个字符的出现次数。
需要注意的是,该程序只适用于 ASCII 字符集,对于 Unicode 字符集需要使用其他方法进行处理。
相关问题
统计字符出现次数C++
以下是C++中统计字符出现次数的例子:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
string s = "aabbbcddddeeffffghijklmnopqrst";
unordered_map<char, int> mp;
for (char c : s) {
mp[c]++;
}
char max_char = ' ';
int max_count = 0;
for (auto p : mp) {
if (p.second > max_count) {
max_count = p.second;
max_char = p.first;
}
}
cout << "出现最多的字符是:" << max_char << endl;
cout << "出现次数为:" << max_count << endl;
return 0;
}
```
文章中出现字符概率统计c++
好的,我可以为您提供一个简单的字符概率统计的C++代码示例:
```c++
#include <iostream>
#include <fstream>
#include <map>
#include <iomanip>
using namespace std;
int main() {
string filename = "example.txt"; // 文本文件路径
map<char, int> freq; // 存储字符出现次数的映射表
int total_chars = 0; // 总字符数
// 读取文本文件,统计字符出现次数
ifstream file(filename);
if (file) {
char c;
while (file.get(c)) {
if (isalpha(c)) { // 只统计字母
freq[tolower(c)]++; // 转换为小写并增加对应计数
total_chars++; // 总字符数增加
}
}
file.close();
// 输出每个字符的出现次数和概率
cout << "字符\t出现次数\t概率" << endl;
for (auto& p : freq) {
char c = p.first;
int count = p.second;
double prob = (double)count / total_chars;
cout << c << "\t" << count << "\t\t" << fixed << setprecision(4) << prob << endl;
}
} else {
cerr << "无法打开文件 " << filename << endl;
return 1;
}
return 0;
}
```
这个代码示例可以读取一个文本文件,统计其中每个字母出现的次数以及对应的概率,并输出到控制台。您可以根据需要进行修改和扩展。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_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)