找出字符串中出现次数最多的字符 c语言

如题所述

#include<iostream>

#include<string>

using namespace std;

void main(void)

{

char testStr[100] = { "We are happppppppppy." };

int aToZ[256]; //初始化一个 int aToZ[256]并清零,对应256个字符的ASCII值;

int maxArrayNum;

int count = 256;

while (count--)

{

aToZ[count] = 0;

}

//遍历字符串数组,并相应在aToZ[i]中计数;

for (int i = 0; testStr[i] != '\0'; i++)

{

aToZ[testStr[i]]++;

}

//找出aToZ[]中的最大值;

maxArrayNum = 0;

for (int i = 0; i < 256; i++)

{

if (aToZ[i] > aToZ[maxArrayNum])

maxArrayNum = i;

}

//输出,完成。

cout << "The original string: " << testStr << endl;

cout << "The times that the most frequent char shows up: "<<aToZ[maxArrayNum] << endl;

char i = maxArrayNum;

cout <<"The most frequent char: "<< i << endl;

}

运行效果:

扩展资料:

while语句若一直满足条件,则会不断的重复下去。但有时,需要停止循环,则可以用下面的三种方式:

一、在while语句中设定条件语句,条件不满足,则循环自动停止。

如:只输出3的倍数的循环;可以设置范围为:0到20。

二、在循环结构中加入流程控制语句,可以使用户退出循环。

1、break流程控制:强制中断该运行区内的语句,跳出该运行区,继续运行区域外的语句。

2、continue流程控制:也是中断循环内的运行操作,并且从头开始运行。

三、利用标识来控制while语句的结束时间。

参考资料来源:

百度百科——while

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-03
#include <stdio.h>
void main()
{
printf("输入字符串:");
char cs[1024];
scanf("%s", cs);
int count[256] = { 0 };
for (int i = 0; cs[i]; i++)
{
count[cs[i]]++;
}
int max = -1;
char c = 0;

for (int i = 0; i<256; i++)
{
if (count[i] > max) {
max = count[i];
c = (char)i;
}
}
printf("出现次数最多的是:%c", c);
int i;
scanf("%d", &i);
}

好了,刚刚写的……

本回答被网友采纳
第2个回答  2018-03-02
#include <stdio.h> 
void main() 
{
char cs[1024];
int count[256] = { 0 };
int i;
int max = -1;
char c = 0;
printf("输入字符串:\n");
scanf("%s", cs);
for (i=0; cs[i]; i++)
{
count[cs[i]]++;
}
for (i=0; i<256; i++)
{
if (count[i] > max)
{
max = count[i];
c = (char)i;
}
}
printf("出现次数最多的字符是:%c\n", c);
printf("出现次数为%d次\n",max);
}