[演算法笔记]统计字母数量

#include <iostream>

using namespace std;

void count_letter_frequency()
{
    char s[101] = {};
    int c[26] = {};
    
    cin >> s; 

    for (int i = 0; s[i]; i++){
        if (s[i] >= 'A' && s[i] <= 'Z'){
            s[i] = s[i] - 'A' + 'a';
        }
    }

    for  (int i = 0; s[i]; i++) {
        if (s[i] >= 'a' && s[i] <= 'z'){
            c[s[i] - 'a'] ++;
        }
    }

    for (int i = 0; i < 26; i++){
        cout << (char) ('a' + i) << ':' << c[i] << endl;
    } 

    
}
void count_letter()
{
    char s[15] = "Hello World!";
 
    // 字母統一換成小寫
    for (int i=0; s[i]; i++)
        if (s[i] >= 'A' && s[i] <= 'Z')
            s[i] = s[i] - 'A' + 'a';
 
    // 枚舉26種英文字母
    for (int i=0; i<26; i++)
    {
        // 枚舉字串的所有字元
        int c = 0;
        for (int j=0; s[j]; j++)
            if (s[j] == 'a' + i)
                c++;
 
        // 印出一種字母的數量
        cout << (char)('a' + i) << ':' << c;
    }
}

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注