【发布时间】:2017-11-21 08:52:31
【问题描述】:
//Program to find max occurring character in string
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 100 // Maximum string size, change to make string smaller or larger
#define MAX_CHARS 255 // Maximum characters allowed for characters
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do{
clrscr();
i=0;
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
i=0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
i++;
}
// Finds maximum frequency of character
max = 0;
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] > freq[max])
max = i; //to print no. of times
}
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
}while(ch=='Y'||ch=='y');
}
当我给它输入:“aaaaeeee”时,输出是“a”出现 4 次,但“e”也出现 4 次。我知道这是按 ascii 值排序的,这就是为什么它给出“a”作为输出,但是当这种情况发生时,我能在这个程序中做什么,输出同时给出“a”和“e”作为输出?
【问题讨论】:
-
旁注:不要使用 void main(),使用 int main()..以及
conio.h标头。 -
我是编码新手,有什么区别?
-
请过这个问题,这里详细讨论了main的返回类型:stackoverflow.com/questions/204476/…
-
永远,永远,永远不要使用
gets,使用fgets(或POSIXgetline)gets是如此不安全且易受缓冲区溢出的影响,它已从C11中删除图书馆。扔了它。如果你的教授想让你使用它,也扔给他。 -
这不是大学工作或任何东西,它是出于我自己学习编码的好奇心,我会照顾它的。
标签: c