计算C++中每个字母表的出现次数

Count the appearance of each alphabet in C++

本文关键字:字母表 C++ 计算      更新时间:2023-10-16

我正在尝试用c++编写一段代码,该代码接受用户的字符串输入,并按字母顺序排列字符串。现在我想扩展这段代码,给我输出"a"出现的次数等等,但我无法扩展它。可能有很多方法可以处理这个问题,但如果有人能指导我如何使用数组处理这个问题的话,请告诉我。

#include <iostream>
#include <sstream>
#include <string>
#include <map>
using namespace std;
int main()
{
    cout << " please enter your charactor " << endl;
    string ch;
    getline(cin, ch);
    int i, step, temp;
    for (step = 0; step<ch.size() - 1; ++step)
        for (i = 0; i<ch.size()- step - 1; ++i)
        {
            tolower(ch[1]);
            if (tolower(ch[i])>tolower(ch[i + 1]))   
            {
                temp = ch[i];
                ch[i] = ch[i + 1];
                ch[i + 1] = temp;
            }
        }
    // count the appearance of each letter using array
    cout << " total lenght of your string's charactor is " << ch.length() << endl;
    system("pause");
}

这就是您所需要的

#include <iostream>
#include <string>
using namespace std;
int main()
{
    // you could easily use a vector instead of an array here if you want.  
    int counter[26]={0};
    string my_string = "some letters";
    for(char c : my_string) {
        if (isalpha(c)) {
            counter[tolower(c)-'a']++;
        }
    }

    // thanks to @James
    for (int i = 0; i < 26; i++) 
    { 
        cout << char('a' + i) << ": " << counter[i] << endl; 
    }
}

从字符中减去CCD_ 1将字母CCD_。打印回时,可以将字母'a'添加回该位置。

使用基于范围的for循环需要c++11,但也可以使用传统的for循环。

从技术上讲,这只适用于字母表中26个或更少字母的语言。。。