计算文本行中每个显示的字符的出现

时间:2019-02-19 02:24:36

标签: c++

如何计算仅给定句子中字母的出现次数?我所做的显示了字母的每个字母,甚至没有给出正确的出现

void testing()
{
    char temp1[100];

    cout << "\nEnter a line of text: \n";
    cin.getline(temp1, 100);

    vector<int> charCount;
    for (int i = 0; i < 26; i++)
    {
        charCount.push_back(0);
    }
    for (size_t i = 0; i < strlen(temp1); i++)
    {
        char currentChar = tolower(temp1[i]);
        if (isalpha(currentChar))
        {
            charCount[currentChar - 'a'];
        }
    }
    for (size_t i = 0; i < charCount.size(); i++)
    {
        cout << charCount[i] << static_cast<char>(i + 'a') << endl;
    }
}

进行一些更改后,似乎只显示字母(e)的出现,但仍不正确。

vector<int> charCount;
for (int i = 0; i < 26; i++) {
    charCount.push_back(0);
}
for (size_t i = 0; i < strlen(temp1); i++) {
    char currentChar = tolower(temp1[i]);
    if (isalpha(currentChar)) {
        charCount[currentChar - 'a']++;
    }
    if (charCount[i]) {
        cout << charCount[i] << " " << static_cast<char>(i + 'a') << endl;
    }
}

0 个答案:

没有答案
相关问题