C++計(jì)算每個(gè)字符出現(xiàn)的次數(shù)
更新時(shí)間:2016年05月02日 17:52:18 作者:王勛廣
這篇文章主要介紹了C++計(jì)算每個(gè)字符出現(xiàn)的次數(shù)的相關(guān)資料,需要的朋友可以參考下
本文實(shí)例為大家分享了C++計(jì)算每個(gè)字符出現(xiàn)的次數(shù)的實(shí)現(xiàn)代碼,供大家參考,具體內(nèi)容如下
#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']++; //經(jīng)典
}
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;
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
C++實(shí)現(xiàn)十進(jìn)制數(shù)轉(zhuǎn)換為二進(jìn)制數(shù)的數(shù)學(xué)算法
這篇文章和大家分享一下我個(gè)人對(duì)十進(jìn)制數(shù)轉(zhuǎn)換為二進(jìn)制數(shù)的想法,目前暫時(shí)更新只整數(shù)十進(jìn)制的轉(zhuǎn)換,后續(xù)會(huì)更新帶有小數(shù)的進(jìn)制轉(zhuǎn)換,代碼使用c++實(shí)現(xiàn)2021-09-09
c++ 虛函數(shù),虛表相關(guān)總結(jié)
這篇文章主要介紹了c++ 虛函數(shù),虛表的的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用c++,感興趣的朋友可以了解下2021-03-03
C++ 17標(biāo)準(zhǔn)正式發(fā)布! 更簡(jiǎn)單地編寫和維護(hù)代碼
C++ 17 標(biāo)準(zhǔn)正式發(fā)布:終于能更簡(jiǎn)單地編寫和維護(hù)代碼了!本文為大家介紹了C ++ 17 主要特性,感興趣的小伙伴們可以參考一下2017-12-12

