C++计算每个字符出现的次数
本文实例为大家分享了C++计算每个字符出现的次数的实现代码,供大家参考,具体内容如下
#include<iostream> //#include<cstdlib> #include<ctime> usingnamespacestd; constintNUMBER_OF_LETTERS=26; constintNUMBER_OF_RANDOM_LETTERS=100; voidcreateArray(char[]); voiddisplayArray(constchar[]); voidcountLetters(constchar[],int[]); voiddisplayCounts(constint[]); intmain() { charchars[NUMBER_OF_RANDOM_LETTERS]; createArray(chars); cout<<"Thelowercaselettersare:"<<endl; displayArray(chars); intcounts[NUMBER_OF_LETTERS]; countLetters(chars,counts); cout<<"\nTheoccurrencesofeachletterare:"<<endl; displayCounts(counts); return0; } voidcreateArray(charchars[]) { srand((unsignedint)time(0)); for(inti=0;i<NUMBER_OF_RANDOM_LETTERS;i++) { chars[i]=static_cast<char>('a'+rand()%('z'-'a'+1)); } } voiddisplayArray(constcharchars[]) { for(inti=0;i<NUMBER_OF_RANDOM_LETTERS;i++) { if((i+1)%20==0) cout<<chars[i]<<""<<endl; else cout<<chars[i]<<""; } } voidcountLetters(constcharchars[],intcounts[]) { for(inti=0;i<NUMBER_OF_LETTERS;i++) counts[i]=0; for(inti=0;i<NUMBER_OF_RANDOM_LETTERS;i++) counts[chars[i]-'a']++;//经典 } voiddisplayCounts(constintcounts[]) { for(inti=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; }
以上就是本文的全部内容,希望对大家的学习有所帮助。