The Program in C++ Program to find a word in a given string which has the highest number of repeated letters is given below:
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
std::string highest_repeated_word(const std::string& str) {
std::unordered_map<std::string, int> word_counts;
std::vector<std::string> words;
std::string current_word;
// Split the string into separate words
for (const char c : str) {
if (c == ' ') {
words.push_back(current_word);
current_word.clear();
} else {
current_word += c;
}
}
words.push_back(current_word);
// Count the number of repeated letters in each word
for (const std::string& word : words) {
std::unordered_map<char, int> letter_counts;
for (const char c : word) {
++letter_counts[c];
}
int max_count = 0;
for (const auto& [letter, count] : letter_counts) {
max_count = std::max(max_count, count);
}
word_counts[word] = max_count;
}
// Find the word with the highest number of repeated letters
std::string highest_repeated_word;
int max_count = 0;
for (const auto& [word, count] : word_counts) {
if (count > max_count) {
highest_repeated_word = word;
max_count = count;
}
}
return highest_repeated_word;
}
int main() {
std::string str;
std::getline(std::cin, str);
std::cout << "Well, the word with the highest number of repeated letters is: "
<< highest_repeated_word(str) << std::endl;
return 0;
}
Output:
Coding has been very much exciting
Well, the word with the highest number of repeated letters is: exciting
Pro-Tips💡
This program uses an unordered_map
to keep track of the number of repeated letters in each word, and then finds the word with the highest count.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.