您的位置:首页 > 其它

华为OJ平台试题 —— 排序:字符统计

2015-08-15 22:33 363 查看
字符统计



代码:

#include<stdio.h>
#include <string.h>

/*
* 定义一个结构体:字符和字符数目
*/
struct CountChar
{
int c;
int count;
};

/* 根据结构体里面的数字的大小,对结构体进行排序 */   <span style="color:#ff0000;"> /* 结构体是可以整体进行搬移排序的 */</span>
void sort(struct CountChar chara[], int n )
{

int i, j;
struct CountChar temp;

for( i = 0; i < n; i++)
for(j = i; j < n ; j++)
{
if(chara[i].count < chara[j].count )
{

temp     = chara[i];
chara[i] = chara[j];
chara[j] = temp;
}
}
}

/*
* 统计字符函数,由主函数传递输入字符
* 返回字符和字符数目
*/

int main(void)
{
struct CountChar a[256];  /* 定义一个结构体数组,该数组有236个元素,均为struct CountChar 类型数据 */
char   b[200];
int    i;

/* 将结构体数组初始化 */
for(i = 0; i < 256; i++)
{
a[i].c= 0;
a[i].count=0;
}

gets(b);  /* 输入字符串 */

/* 将每个字符赋值给tmp,同时对其数目进行统计,a[tmp],tmp为ASCII值,每个字符都有一个结构体  */
for(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].c = b[i];
a[tmp].count++;
}
}

/* 对统计出来的数字进行排序 */
sort(a, 256);
 
/* 输出字符 */
for(i = 0; i < 256; i++)
{
if(a[i].count != 0)
printf("%c", (a[i].c));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: