字符统计

来源:互联网 发布:js通过class获取元素 编辑:程序博客网 时间:2024/06/04 18:11

题目

描述

如果统计的个数相同,则按照ASII码由小到大排序输出 。如果有其他字符,则对这些字符不用进行统计。
实现以下接口:
输入一个字符串,对字符中的各个英文字符,数字,空格进行统计(可反复调用)
按照统计个数由多到少输出统计结果,如果统计的个数相同,则按照ASII码由小到大排序输出
清空目前的统计结果,重新统计
调用者会保证:
输入的字符串以‘\0’结尾。

输入

输入一串字符。

输出

对字符中的
各个英文字符(大小写分开统计),数字,空格进行统计,并按照统计个数由多到少输出,如果统计的个数相同,则按照ASII码由小到大排序输出 。如果有其他字符,则对这些字符不用进行统计。

样例输入

aadddccddc

样例输出

dca

思路

利用自带函数

代码

#include <iostream>#include <map>using namespace std;int main(){    //利用STL自带的排序功能    map<char,int,greater<int>> m;    string str;    //输入    getline(cin,str);    for(string::iterator iter = str.begin(); iter!=str.end(); ++iter)    {        if(m.find(*iter)==m.end())        {            m[*iter]=1;        }        else        {            m[*iter]++;        }    }    //输出    for(map<char,int,greater<int>>::iterator iter = m.begin(); iter!=m.end(); ++iter)    {        cout<<iter->first;    }    cout<<endl;    return 0;}

这里写图片描述

#include <iostream>#include <algorithm>#include <cstdio>using namespace std;struct Count{    int ch;    int counter;};bool cmp(const Count &a,const Count &b){    return a.counter>b.counter;}int main(){    struct Count a[256];    char b[256];    //初始化数组    for(int i=0; i<256; i++)    {        a[i].ch=i;        a[i].counter=0;    }    gets(b);    //计数    for(int i=0; b[i]!='\0'; i++)    {        if((b[i]>='a'&&b[i]<='z') || (b[i]>='A'&&b[i]<='Z') || (b[i]>='0'&&b[i]<='9') || b[i]==' ')        {            char tmp=b[i];            a[tmp].counter++;        }    }    //排序    sort(a,a+256,cmp);    //输出    for(int i=0; i<256; i++)    {        if(a[i].counter!=0)        {            cout<<char(a[i].ch);        }    }}

这里写图片描述

0 0