C++計(jì)算每個(gè)字符出現(xiàn)的次數(shù)
本文實(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)并分析
這篇文章主要介紹了C++ 中二分查找遞歸非遞歸實(shí)現(xiàn)并分析的相關(guān)資料,需要的朋友可以參考下2017-06-06
關(guān)于C++的強(qiáng)制類型轉(zhuǎn)換淺析
C++的強(qiáng)制類型轉(zhuǎn)換是我們?cè)谌粘i_(kāi)發(fā)中經(jīng)常會(huì)遇到的,下面這篇文章主要給大家介紹了關(guān)于C++強(qiáng)制類型轉(zhuǎn)換的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
Visual Studio Code (VSCode) 配置搭建 C/C++ 開(kāi)發(fā)編譯環(huán)境的流程
記得N年前剛開(kāi)始接觸編程時(shí),使用的是Visual C++6.0,下面這個(gè)可愛(ài)的圖標(biāo)很多人一定很熟悉。不過(guò)今天想嘗鮮新的工具 Visual Studio Code 來(lái)搭建C/C++開(kāi)發(fā)環(huán)境,感興趣的朋友一起看看吧2021-09-09
C語(yǔ)言實(shí)現(xiàn)數(shù)組的循環(huán)移位的方法示例
這篇文章主要介紹了C語(yǔ)言實(shí)現(xiàn)數(shù)組的循環(huán)移位的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
C++實(shí)現(xiàn)一個(gè)線程安全的單例工廠實(shí)現(xiàn)代碼
這篇文章主要介紹了 C++實(shí)現(xiàn)一個(gè)線程安全的單例工廠實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05
c語(yǔ)言實(shí)現(xiàn)簡(jiǎn)易版三子棋(附完整代碼)
大家好,本篇文章主要講的是c語(yǔ)言實(shí)現(xiàn)簡(jiǎn)易版三子棋(附完整代碼),感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-01-01

