c/c++实现统计英文字符串并降序输出

输入一个英文字符串(不含空格及标点),若是大写的全部变成小写,然后统计该字符串中出现的字符及其个数,并且降序输出
本程序要用C/C++来实现,要求为:
比如,输入:hlghldHLhdh
输出时格式:
h数目为:5
l数目为:3
d数目为:2
g数目为:1
希望各位高手尽快给出答案,感激不尽!!!

第1个回答  2010-06-28
#include<iostream>
#include<string>//字符串头文件
#include<algorithm>//sort函数头文件
using namespace std;
struct node{
int times;//次数
int num;//号码 0~25 代表a~z
node(){times=0;}//构造函数让每个结构体对象初始times为0
}a[26];
bool op(node a,node b){//排序条件
return a.times>b.times;
}
int main()
{
string s;//字符串
for(int i=0;i<26;i++)
a[i].num=i;
while(cin>>s){
for(int i=0;i<s.size();i++){
s[i]=tolower(s[i]);//让每个字符变成小写字母
a[s[i]-'a'].times++;
}
cout<<"改变后的字符串为:"<<endl;
cout<<s<<endl;
sort(a,a+26,op);//对26个字母以times降序来排序
for(int i=0;i<26;i++)//最后输出
if(a[i].times)
cout<<(char)(a[i].num+'a')<<"数目为: "<<a[i].times<<endl;
}
system("pause");
}本回答被提问者采纳
第2个回答  2010-06-28
#include <iostream>
using namespace std;

int cnt[26]={0};
char ch[26]="";

void sort(int a[],char b[],int size);
void count(char);

int main()
{
cout<<"Please input a string:"<<endl;
char s[]="";
cin.getline(s,1000);
int n=-1;
while (s[++n])
{
if ('A' <= s[n] && 'Z' >= s[n] )
s[n]+=32;
if ('a' <= s[n] && 'z' >= s[n] )
count(s[n]);
}

sort(cnt,ch,26);

n=-1;
while (cnt[++n])
{
cout<<ch[n]<<"的数目为:"<<cnt[n]<<endl;
}
return 0;
}

void count(char s)
{
for (int i = 0;i <26; i++)
{
if (s == i+97)
{
cnt[i]++;
ch[i]=s;
}
}
}

void sort(int a[],char b[],int size)
{
for (int i = 0; i < size - 1; i++)
{
int s = i;
for (int j = i + 1; j < size; j++)
if (a[j] > a[s])
s = j;
int temp = a[i];
a[i] = a[s];
a[s] = temp;
temp = b[i];
b[i] = b[s];
b[s] = temp;
}
}
第3个回答  2010-06-28
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

char alphabet[]={'a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z'};
int ab_number[26]={0};

int main(void)
{
string c;
int i;

cin>>c;
transform(c.begin(),c.end(),c.begin(),tolower);
for(i=0;i<c.size();i++)
if(c[i]>='a' && c[i]<='z')
ab_number[c[i]-'a']++;

for(i=0;i<26;i++)
{
for(int j=i+1;j<26;j++)
{
if(ab_number[i]<ab_number[j])
{
int temp_n=ab_number[i];
ab_number[i]=ab_number[j];
ab_number[j]=temp_n;
char temp_c=alphabet[i];
alphabet[i]=alphabet[j];
alphabet[j]=temp_c;
}
}
}

for(i=0;i<26;i++)
{
if(ab_number[i]!=0)
cout<<alphabet[i]<<":"<<ab_number[i]<<endl;
}

return 0;
}
相似回答