统计每个字符出现的次数

wxyjiayou 2010-11-24 07:30:57
请高手帮忙啊,
谁帮我编个程序啊,用C语言

已知一个数组,统计数组中每个字符出现次数,数组中字符不只限于英文字母 可以包含任何一种符号

...全文
412 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxyjiayou 2010-11-24
  • 打赏
  • 举报
回复
为什么62 按2 处理呀?
wxyjiayou 2010-11-24
  • 打赏
  • 举报
回复
谢谢谢谢 真好 呵呵
全给你啦
we_sky2008 2010-11-24
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 wxyjiayou 的回复:]
我明白了 谢谢 ,确实很好 呵呵
不过我随便弄了一个
#include<stdio.h>
#include<string.h>

void main()
{
char *src,a[20]={'a','g','d','e','s','a','f','r','d','a','d','g','5','5','62','1','f','6','e','f'};
src=a;
c……
[/Quote]
数组的话可以这样用:

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

void func(const char *src, int size)
{
unsigned char all[256] = {0};
int i;
if (src == NULL)
return;
while (size--)
{
++all[*(src + size)];
}
for (i = 0; i < 256; i++)
{
if (all[i] != 0)
{
printf("字符%c出现次数: %d\n", i, all[i]);
}
}
}

int main()
{
char a[20]={'a','g','d','e','s','a','f','r','d','a','d','g','5','5','62','1','f','6','e','f'};//'62'可能按'2'来处理
func(a, sizeof a / sizeof a[0]);

system("pause");
return 0;
}


漫步者、 2010-11-24
  • 打赏
  • 举报
回复

//,用每个字符的与'0'相减,得出数组的下标,然后在相减之后“++数组”就可以得出每个字符的出现的次数!
漫步者、 2010-11-24
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 leonardo_lynn 的回复:]
#include<stdio.h>
int main()
{
int count=0;
while(getchar()!='\n')
count++;
printf("The number of Characters you have input is: %d",count);
return 0;
}
[/Quote]/// 不懂这是什么!
wxyjiayou 2010-11-24
  • 打赏
  • 举报
回复
我明白了 谢谢 ,确实很好 呵呵
不过我随便弄了一个
#include<stdio.h>
#include<string.h>

void main()
{
char *src,a[20]={'a','g','d','e','s','a','f','r','d','a','d','g','5','5','62','1','f','6','e','f'};
src=a;
char all[256] = {0};
int i;

while (*src)
{
++all[*src];
++(src);
}
for (i = 0; i < 256; i++)
{
if (all[i] != 0)
{
printf("字符%c出现次数: %d\n", i, all[i]);
}
}
}



可是为什么‘62’没有输出,而且输出还多了两种字符





hdusunny44 2010-11-24
  • 打赏
  • 举报
回复
LZ没认真看代码啊。。。。。
leonardo_Lynn 2010-11-24
  • 打赏
  • 举报
回复

void func(const char *src)
{
unsigned char all[256] = {0};
int i;
if (src == NULL)
return;
while (*src)
{
++all[*src]; //这是每种字符出现次数所存储的数组
++src; //这是所有字符存储的地方
}
for (i = 0; i < 256; i++)
{
if (all[i] != 0)
{
printf("字符%c出现次数: %d\n", i, all[i]);
}
}
}



楼主仔细品味,3楼代码很漂亮,赞一个。
wxyjiayou 2010-11-24
  • 打赏
  • 举报
回复
不对,数组中有可能相同的项

上边写的只是默认 每一个是不同的
zmkkobe 2010-11-24
  • 打赏
  • 举报
回复
楼上正解,呵呵
we_sky2008 2010-11-24
  • 打赏
  • 举报
回复

void func(const char *src)
{
unsigned char all[256] = {0};
int i;
if (src == NULL)
return;
while (*src)
{
++all[*src];
++src;
}
for (i = 0; i < 256; i++)
{
if (all[i] != 0)
{
printf("字符%c出现次数: %d\n", i, all[i]);
}
}
}

Qyee 2010-11-24
  • 打赏
  • 举报
回复
char c=getchar();

循环查c是否出现在已经出现保存的字符的数组中,是个数+1 否 加入字符数组,个数设置为1.直到数组结尾。
leonardo_Lynn 2010-11-24
  • 打赏
  • 举报
回复
#include<stdio.h>
int main()
{
int count=0;
while(getchar()!='\n')
count++;
printf("The number of Characters you have input is: %d",count);
return 0;
}

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧