#include <iostream>
#include <string>
// Class to analyze letter statistics in a string
class letter_stats {
private:
char letter1, letter2; // Two character variables
std::string text; // String variable
public:
// Constructor to initialize private variables
letter_stats(char l1, char l2, std::string str) : letter1(l1), letter2(l2), text(str) {}
// Function that prints the values of private variables
void print_word() const {
std::cout << "Letter 1: " << letter1 << "\n";
std::cout << "Letter 2: " << letter2 << "\n";
std::cout << "Text: " << text << "\n";
}
// Function to check if a letter exists in the string
bool letter_exists(int index) const {
char selected_letter;
if (index == 1) {
selected_letter = letter1;
} else {
selected_letter = letter2;
} // Select appropriate letter
return text.find(selected_letter) != std::string::npos; // Check if letter is in string
}
// Function to find the last occurrence of a letter in the string
int letter_index(int index) {
char selected_letter;
if (index == 1) {
selected_letter = letter1;
} else {
selected_letter = letter2;
} // Select appropriate letter
return text.rfind(selected_letter); // Find last occurrence
}
};
int main() {
char l1, l2;
std::string user_text;
// Getting user input for letters and text
std::cout << "Enter the first letter: ";
std::cin >> l1;
std::cout << "Enter the second letter: ";
std::cin >> l2;
std::cout << "Enter a sequence of characters (no spaces): ";
std::cin >> user_text;
// Creating an object of letter_stats class
letter_stats stats(l1, l2, user_text);
// Display stored values
stats.print_word();
// Check and print if the letters exist in the string
for (int i = 1; i <= 2; ++i) {
if (stats.letter_exists(i)) {
std::cout << "Letter " << (([&]() { if (i == 1) return l1; else return l2; }())) << " found in the string.\n";
} else {
std::cout << "Letter " << (([&]() { if (i == 1) return l1; else return l2; }())) << " not found in the string.\n";
}
}
// Print the last index of each letter
for (int i = 1; i <= 2; ++i) {
int index = stats.letter_index(i);
if (index != -1) {
std::cout << "Last occurrence of letter " << (([&]() { if (i == 1) return l1; else return l2; }())) << " is at index " << index << "\n";
} else {
std::cout << "Letter " << (([&]() { if (i == 1) return l1; else return l2; }())) << " not found in the string.\n";
}
}
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: