Reputation: 51
I have a complex C
program, and i wanna write only a function which gets a string as a parameter.
int most_frequent(char *string)
The function has to return the number of the most frequent character in the string. I tried something like this, but this is incorrect i think:
int most_frequent(char *string){
int i, lenght;
lenght=strlen(string);
int max=0, x=0;
for(i=0;i<lenght;i++)
{
if(string[i]==string[i++])
{
x++;
}
if(max<x)
max=x;
}
return max;
}
for example: "overflow" - 2 "eleven" - 3
Upvotes: 0
Views: 2872
Reputation:
Do following:
// version that ignores the upper and lower case
int most_frequent(char *string) {
int letterCout[26];
// counts occurrence of each letter
for (int i = 0; i < strlen(string); ++i){
// this counts characters if you are ignoring the case (upper or lower)
if (string[i] >= 'a' && string[i] =< 'z')
alphabet [string[i] - 'a']++;
else if (string[i] >= 'A' && string[i] =< 'Z')
alphabet [string[i] - 'A']++;
}
// finds which letter occurred the most
int max = 0;
for (int i = 0; i < strlen(string); ++i)
if (letterCoutn[i] > max)
max = letterCount[i];
return max;
}
or you can do this:
// version which does not ignore case but count the separately
int most_frequent(char *string) {
int letterCout[52]; // 52 so you can count upper and lower case
// counts occurrence of each letter
for (int i = 0; i < strlen(string); ++i){
if (string[i] >= 'a' && string[i] <= 'z')
alphabet [string[i] - 'a' + 26]++; // plus 26 so to offset in array so upper case could be counted in lower half of an array.
else if (string[i] >= 'A' && string[i] <= 'Z')
alphabet [string[i] - 'A']++;
}
// finds which letter occurred the most
int max = 0;
for (int i = 0; i < strlen(string) * 2; ++i)
if (letterCoutn[i] > max)
max = letterCount[i];
return max;
}
Upvotes: 2
Reputation: 582
I assume that you have a string that follows ASCII. In this way, there are 256 possible values for each char. Thus we count the frequency of each and return the largest one.
int most_frequent(char *string){
int count[256] = {0}; // Assum char is ASCII
int max = 0;
int i;
for(i=0; i < strlen(string) ;i++) {
count[(unsigned char)(string[i])] ++;
}
for(i=0; i < 256 ;i++) {
if (count[i] > max)
max = count[i];
}
return max;
}
Upvotes: 4