首页 > 解决方案 > 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;  
}

标签: c++

解决方案


即使这不是一个好的代码,你也要求只有这 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提到的使用地图,但我使用了一个小数组来模拟地图。


推荐阅读