想用map做,无奈不怎么会map,我也是几天前才看了map。自己写的错误代码如下。
<pre name="code" class="cpp">#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<char, int> char_count;
string s;
int i;
while(cin >> s) {
for(i=0;i<=25; i++){
char_count.insert({'a'+i, 0});
}
for(auto &c : s)
++char_count[c];
for(const auto &c : char_count)
cout << c.first << ":" << c.second << endl;
}
return 0;
}
在网上找的如下,就没用map。
#include <stdio.h>
#include <string.h>
#define N 100001
int main()
{
char s[N];
int letter[26],i;
while(gets(s))
{
memset(letter, '\0', sizeof(letter)) ;
for(i=0; s[i]!='\0'; i++)
if(s[i]>='a' && s[i]<='z')
letter[ s[i]-'a' ]++;
for(i=0;i<26;i++)
printf("%c:%d\n",'a'+i, letter[i]);
printf("\n");
}
return 0;
}