您的位置:首页 > 编程语言 > C语言/C++

C/C++面试题(4)——统计输入字符串中字符的频度

2016-09-01 11:16 260 查看
这是一道很普通的题目,这里给出的代码的一个关键点就是使用字符的ASCII码作为数组的下标直接对应该字符。

#define  _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>

struct Freq
{
char alpha;
int freq;
};
typedef struct Freq FREQ;

void showFreq(FREQ *freq, int cnt);
FREQ *getFreq(char *str, int *cnt);

void showFreq(FREQ *freq, int cnt)
{
printf("\n字符\t频度\n");
if (NULL == freq)
{
printf("error: freq is NULL\n");
return;
}

for (int i = 0; i < cnt; i++)
printf("%c\t%d\n", freq[i].alpha, freq[i].freq);
}

//获取字符串str中字符出现的频度
FREQ *getFreq(char *str, int *cnt)
{
FREQ *frp = NULL;
int count = 0;
int zf[128] = { 0 };
int i, t;
if (NULL == str || NULL == cnt)
{
printf("error: str || cnt is NULL\n");
return NULL;
}
/*
直接通过字符的ASCII码 作为数组的下标
这里计算的是同一种字符出现的次数
*/
for (i = 0; str[i]; i++)
{

zf[str[i]]++;//例如"AAA"那么 zf[65]++ 达到3
//如果是A的话,zf[A]即是zf[65]++
}

/*
这里计算的是字符的和种类
*/
for (i = 0; i < 128; i++)
{
//如果zf[i]不等于0的话,说明有这个字符的出现,
//这样就可以计算出字符的种类了
if (zf[i])
count++;
}

if( frp = (FREQ *)malloc(sizeof(FREQ)* count))
for (i = t = 0; i < 128; i++)
{
if (zf[i])
{
frp[t].alpha = i;		//当前字符
frp[t++].freq = zf[i];	//当前字符频度
}
}
*cnt = count;
return frp;
}

void main()
{
char str[80];
FREQ *freqp;
int cnt;	//统计字符种类

puts("输入一个字符串:");
gets(str);

freqp = getFreq(str, &cnt);

showFreq(freqp, cnt);

if (freqp)
free(freqp);
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  CC++面对试题
相关文章推荐