c++ - c ++程序计算字母字符的出现次数
问题描述
创建一个程序,计算字母字符的出现次数,计算 C++ 中字符串中的字母
我遇到了不同的代码,但对我们的教授没有什么好处,我的教授只想要
#include <iostream>
用户输入#include<conio.h>
的using namespace std;
字母是打印或输出的字母
也许这会有所帮助,这是我教授以前的代码:
for(int y=0; y<=9; y++){
int counter=0;
for (int x=0; x<=99;x++){
if (refchar[y]==userchar[x]){
counter++;
}
}
cout<<refchar[y]<<"="<<counter <<"\n";
}
getch();
return 0;
}
这是我的代码:
int main(){
string refchar="char alphabet[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
'O','P','Q','R','S','T','U','V','W','X','Y','Z'};
";
char userchar[500]="";
cout<<"Enter number:";
cin>>userchar;
for(int y=0; y<=9; y++){
int counter=0;
for (int x=0; x<=99;x++){
if (refchar[y]==userchar[x]){
counter++;
}
}
cout<<refchar[y]<<"="<<counter <<"\n";
}
getch();
return 0;
}
解决方案
即使这不是一个好的代码,你也要求只有这 3 个标题的东西,所以我写了这样的代码:
#include <iostream>
using namespace std;
int main() {
char userchar[500]="";
cin.getline(userchar, sizeof userchar);
int charscnt[128] = {0,};
int idx = 0;
while (userchar[idx] != 0) {
charscnt[static_cast<int>(userchar[idx])]++;
idx++;
}
for (int i = 0; i < sizeof charscnt / sizeof(int); i++) {
if (charscnt[i] != 0) {
cout << static_cast<unsigned char>(i) << "=" << charscnt[i] << endl;
}
}
return 0;
}
逻辑类似于Jasper提到的使用地图,但我使用了一个小数组来模拟地图。
推荐阅读
- json - 如何在 ElasticSearch 中根据电子邮件域名聚合用户日志
- c++ - 液压系统模拟
- python-3.x - Keras 使用没有模型对象的多 GPU(不用于训练)
- javascript - 在 Angular 小写 4、6、7 中输入 URL 时出错
- android - 用于递归绑定到 ListView 的自定义 ArrayAdapter
- regex - tcl 中带有方括号和变量的字符串上的 regsub 问题
- angular - Angular - 提供的数据源与数组、可观察对象或数据源不匹配
- python - Scipy GridData QhullError:中心点与面共面,或顶点与相邻面共面
- c - 为什么多个 fgets 语句会覆盖字符数组?
- php - 如何将表格中选定的行 ID 提供给我的模型?