手机
当前位置:查字典教程网 >编程开发 >C语言 >C++计算每个字符出现的次数
C++计算每个字符出现的次数
摘要:本文实例为大家分享了C++计算每个字符出现的次数的实现代码,供大家参考,具体内容如下#include//#include#includeus...

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

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

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

【C++计算每个字符出现的次数】相关文章:

C语言实现静态链表的方法

C语言中堆空间的生成与释放详解

浅析C++中的虚函数

C++中简单读写文本文件的实现方法

c语言字符数组与字符串的使用详解

C++中汉字字符串的截取

c语言调用汇编的方法

C++ 关于STL中sort()对struct排序的方法

基于C语言字符串函数的一些使用心得

C++中函数模板的用法详细解析

精品推荐
分类导航