c语言问题:一道求给定字符串数组中出现字符数最多的题目

如题,给定字符串长度和字符串,求出现个数最多的字符。
下面是我的代码
#include<stdio.h>
#include<string.h>
int main()
{
int i,n,j,temp,c[100]={0},pos,max;
char a[100],b[100];
scanf("%d",&n);
getchar();
gets(a);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
b[0]=a[0];
for(i=1,j=0;i<n;i++)
{
if(a[i]==a[i-1]) c[j]++;
else
{
j=j+1;
b[j]=a[i];
}
}
pos=0;
max=c[0];
for(i=1;i<=j;i++)
{
if(c[i]>max)
{
max=c[i];
pos=i;
}

}
printf("%c\n",b[pos]);
return 0;
}
可是老师说太复杂,请问各位大侠,有什么简单的方法?

先声明一个数组int arr[200]={0},遍历字符串数组,对于数组中的每一个字符(假设为ch),设置
arr[ch-'\0']自加。最后看arr中哪个元素的值最大,即为出现次数最多的字符啦。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-09-05
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
//
这段进行交换无意义
for(i=1,j=0;i<n;i++)
{
if(a[i]==a[i-1])
c[j]++;
else
{
j=j+1;
b[j]=a[i];
}
}
//
统计所有元素?
for(i=1;i<=j;i++)
{
if(c[i]>max)
{
max=c[i];pos=i;
}
}
//
获取最大值……
三段循环中只有这段才是重点吧
char
repeat_max;
int
repeat_count=0;
int
tmp_count=0;
char
tmp;
for
(i
=
0;i
<
n
-1;
i
++)
{
tmp
=
a[i];
if
(repeat_max
==
tmp)
continue;
tmp_count
=
1;
for
(
j
=
i
+1
;
j
<
n
-1;
j
++)
{
if
(tmp
==
a[j])
tmp_count
+=1;
}
if
(tmp_count
>
repeat_count)
{
repeat_count
=
tmp_count
;
repeat_max
=
tmp;
}
}
第2个回答  2012-12-22
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
// 这段进行交换无意义
for(i=1,j=0;i<n;i++)
{
if(a[i]==a[i-1])
c[j]++;
else
{
j=j+1;
b[j]=a[i];
}
}
// 统计所有元素?
for(i=1;i<=j;i++)
{
if(c[i]>max)
{
max=c[i];pos=i;
}
}
// 获取最大值……
三段循环中只有这段才是重点吧
char repeat_max;
int repeat_count=0;
int tmp_count=0;
char tmp;
for (i = 0;i < n -1; i ++)
{
tmp = a[i];
if (repeat_max == tmp)
continue;

tmp_count = 1;
for ( j = i +1 ; j < n -1; j ++)
{
if (tmp == a[j])
tmp_count +=1;
}
if (tmp_count > repeat_count)
{
repeat_count = tmp_count ;
repeat_max = tmp;
}
}本回答被提问者采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网