// OrinTill Qimid CS1A Chapter 4, P. 294, 10
//
// /**************************************************************
// * MOST FREQUENT CHARACTER FINDER
// *
// * ____________________________________________________________
// * This program uses two overloaded functions to handle both
// * C-string and std::string inputs. The main function demonstrates
// * the functionality by asking the user to enter a string, calling
// * the appropriate function, and displaying the result.
// * ____________________________________________________________
// * INPUT
// * A string provided by the user.
// * OUTPUT
// * The most frequent character in the input string.
// **************************************************************/
#include <iostream>
#include <cstring> // For C-string functions
#include <string> // For std::string
using namespace std;
// Function to find the most frequent character in a C-string
char mostFrequentChar(const char* str) {
int freq[256] = {0}; // Array to store frequency of each ASCII character
// Count character frequencies
for (int i = 0; str[i] != '\0'; i++) {
if (!isspace(str[i])) { // Ignore spaces
freq[static_cast<unsigned char>(str[i])]++;
}
}
// Find the character with the highest frequency
char mostFrequent = '\0';
int maxCount = 0;
for (int i = 0; i < 256; i++) {
if (freq[i] > maxCount) {
maxCount = freq[i];
mostFrequent = static_cast<char>(i);
}
}
return mostFrequent;
}
// Overloaded function to find the most frequent character in a std::string
char mostFrequentChar(const string& str) {
int freq[256] = {0}; // Array to store frequency of each ASCII character
// Count character frequencies
for (char ch : str) {
if (!isspace(ch)) { // Ignore spaces
freq[static_cast<unsigned char>(ch)]++;
}
}
// Find the character with the highest frequency
char mostFrequent = '\0';
int maxCount = 0;
for (int i = 0; i < 256; i++) {
if (freq[i] > maxCount) {
maxCount = freq[i];
mostFrequent = static_cast<char>(i);
}
}
return mostFrequent;
}
int main() {
const int SIZE = 256; // Maximum size for C-string
char cString[SIZE];
string stdString;
// Get input as a C-string
cout << "Enter a string (C-string): ";
cin.getline(cString, SIZE);
// Call the function for C-string
char cStringResult = mostFrequentChar(cString);
cout << "The most frequent character in the C-string: " << cStringResult << endl;
// Get input as a std::string
cout << "Enter a string (std::string): ";
getline(cin, stdString);
// Call the overloaded function for std::string
char stdStringResult = mostFrequentChar(stdString);
cout << "The most frequent character in the std::string: " << stdStringResult << endl;
return 0;
}