欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

统计字符串数组中字母出现的次数

程序员文章站 2022-04-30 20:37:36
...

题目描述:从键盘终端输入字符串,统计相同字符串出现的次数,并按照字母表顺序输出。

输入:THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
输出:
A:1
B:1
C:1
D:1
E:3
F:1
G:1
H:2
I:1
J:1
K:1
L:1
M:1
N:1
O:4
P:1
Q:1
R:2
S:1
T:2
U:2
V:1
W:1
X:1
Y:1
Z:1
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int computeWords(const string& str);
void countOccurs(const string& str, int a[]);
void show(const string& str, const int a[], int LEN);
int main() {
    const int LETTER = 26;
    int a[LETTER] = {0};
    string str;
    cout << "Enter a string: ";
    getline(cin, str);
    int words = computeWords(str);
    countOccurs(str, a);
    cout << words << " words"<<endl;   //输出单词数量 
    show(str, a, LETTER);
    return 0;
}

int computeWords(const string& str) {   //统计单词数量 
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (isalpha(str[i]) && (! isalpha(str[i +1])))  // C语言标准库中isalpha(int c)检查传递的字符是否为字母。
            count++;
    }
    return count;
}

void countOccurs(const string& str, int a[]) {   //统计出现的次数 
    for (int i = 0; i < str.length(); i++) {
        if (isupper(str[i]))   //C语言标准库中isupper(int c) 检查所传的字符是否是大写字母。
            a[str[i] - 'A']++;
        else if (islower(str[i]))  //C语言标准库中islower(int c) 检查所传的字符是否是小写字母。
            a[str[i] - 'a']++;
    }
}
void show(const string& str, const int a[], int LEN) {  //输出函数 
    char letters='A';
    for (int i = 0; i < LEN; i++) {
        if (a[i] != 0)
            cout <<letters<<":"<< a[i]  <<endl;
        letters++;
    }
}

运行截图:
统计字符串数组中字母出现的次数

相关标签: C++