计算C ++中每个字母的外观

时间:2016-05-09 03:00:04

标签: c++ arrays

我正在尝试用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");

}

1 个答案:

答案 0 :(得分:1)

这就是你所需要的一切

#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; 
    }
}

从字符中减去'a',将字母'a'基线定位到数组中的位置0。您可以在将其打印出来时将字母'a'添加回位置。

使用基于范围的for循环需要c ++ 11,但您可以以相同的方式使用传统的for循环。

从技术上讲,这仅适用于字母表中包含26个或更少字母的语言...