#include <iostream>
#include <cstring>
#include <string>
#include <vector>
usingnamespace std;
//Function prototypes
char mostfreq(string);
char mostfreq(char []);
int main()
{
string words;
char freq;
//Generates 100 char space
char letters[100];
/*************************************************************************/
/*******************************STRING************************************/
cout << "Enter anything you want and I will tell you the most frequent letter." << endl;
getline(cin, words);
freq = mostfreq(words);
cout << "The most frequent letter is " << freq << " in a string." << endl;
/*************************************************************************/
/******************************C-STRING***********************************/
for(int i = 0; i < words.length(); i++)
{
letters[i] = words[i];
}
freq = mostfreq(letters);
cout << "The most frequent letter is " << freq << " in a c-string." << endl;
}
char mostfreq(string words)
{
//Tally mark for each letter that appears
int wordTally[26];
int highest = 0;
//Sets Tally Marks to 0
for(int i = 0; i < 26; i++)
{
wordTally[i] = 0;
}
//Changes all words to upper case
for(int j = 0; j < words.length(); j++)
{
if(islower(words[j]))
{
words[j] = toupper(words[j]);
}
}
//Subtracts 65(ASCII Decimal for 'A') and uses that number to mark on Tally
for(int k = 0; k < words.length(); k++)
{
words[k] = words[k] - 65;
wordTally[words[k]]++;
}
//Determines which Tally haves the highest number and will be recorded
for(int l = 1; l < 26; l++)
{
if(wordTally[highest] < wordTally[l])
{
highest = l;
}
}
//The Tally with the highest count will be returned
//Add 65 because it was subtracted earlier
return highest + 65;
}
char mostfreq(char letters[])
{
int wordTally[26];
int highest = 0;
int counter = 0;
//Vector is used to hold all the letters from the given word
std::vector <char> wordCheck;
for(int i = 0; i < 26; i++)
{
wordTally[i] = 0;
}
//Use vector to avoid all non alphabet characters
while(letters[counter] != '\0')
{
if(isalpha(letters[counter]))
{
wordCheck.push_back(letters[counter]);
}
counter++;
}
//Change all lower cases to upper case
for(int j = 0; j < wordCheck.size(); j++)
{
if(islower(wordCheck[j]))
{
wordCheck[j] = toupper(wordCheck[j]);
}
}
//Subtracts 65 to determine where to mark on tally
for(int k = 0; k < wordCheck.size(); k++)
{
wordCheck[k] = wordCheck[k] - 65;
wordTally[wordCheck[k]]++;
}
//Searches for the highest mark on Tally
for(int l = 1; l < wordCheck.size(); l++)
{
if(wordTally[highest] < wordTally[l])
{
highest = l;
}
}
//Returns the most frequent letter
return highest + 65;
}
Here is the result...
1 2 3 4
Enter anything you want and I will tell you the most frequent letter.
sese
The most frequent letter is E in a string.
The most frequent letter is A in a c-string.