C++计算每个字符出现的次数

时间:2021-05-02

本文实例为大家分享了C++计算每个字符出现的次数的实现代码,供大家参考,具体内容如下

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 #include <iostream> //#include <cstdlib> #include <ctime> using namespace std; const int NUMBER_OF_LETTERS = 26; const int NUMBER_OF_RANDOM_LETTERS = 100; void createArray(char []); void displayArray(const char []); void countLetters(const char [], int []); void displayCounts(const int []); int main() { char chars[NUMBER_OF_RANDOM_LETTERS]; createArray(chars); cout << "The lowercase letters are:" << endl; displayArray(chars); int counts[NUMBER_OF_LETTERS]; countLetters(chars, counts); cout << "\nThe occurrences of each letter are:" << endl; displayCounts(counts); return 0; } void createArray(char chars[]) { srand((unsigned int)time(0)); for (int i = 0; i < NUMBER_OF_RANDOM_LETTERS; i++) { chars[i] = static_cast<char>('a' + rand() % ('z' - 'a' + 1)); } } void displayArray(const char chars[]) { for (int i = 0; i < NUMBER_OF_RANDOM_LETTERS; i++) { if ((i + 1) % 20 == 0) cout << chars[i] << " " << endl; else cout << chars[i] << " "; } } void countLetters(const char chars[], int counts[]) { for (int i = 0; i < NUMBER_OF_LETTERS; i++) counts[i] = 0; for (int i = 0; i < NUMBER_OF_RANDOM_LETTERS; i++) counts[chars[i] - 'a']++; //经典 } void displayCounts(const int counts[]) { for (int i = 0; i < NUMBER_OF_LETTERS; i++) { if ((i + 1) % 10 == 0) cout << counts[i] << " " << static_cast<char>(i + 'a') << endl; else cout << counts[i] << " " << static_cast<char>(i + 'a') << " "; } cout << endl; }

以上就是本文的全部内容,希望对大家的学习有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章