print duplicate characters from string in c++
#include <iostream>
#include <unordered_map>
void printDuplicateCharacters(const std::string& str) {
std::unordered_map<char, int> charCount;
for (char ch : str) {
if (++charCount[ch] == 2) {
std::cout << ch << " ";
}
}
}
int main() {
std::string inputString = "hello world";
std::cout << "Duplicate characters in '" << inputString << "': ";
printDuplicateCharacters(inputString);
std::cout << std::endl;
return 0;
}
Explanation:
Header inclusion:
#include <iostream>
: Required for input/output operations.#include <unordered_map>
: Included to use thestd::unordered_map
container.
printDuplicateCharacters
function:void printDuplicateCharacters(const std::string& str)
: Function declaration that takes a constant reference to a string.std::unordered_map<char, int> charCount;
: Initializes an unordered map where characters are keys and their counts are values.
Loop through the string:
for (char ch : str)
: Iterates through each character in the input string.if (++charCount[ch] == 2) { std::cout << ch << " "; }
: Increments the count for each character encountered in the map. If the count reaches 2, prints the character indicating duplication.
main()
function:std::string inputString = "hello world";
: Declares a string variableinputString
initialized with "hello world".std::cout << "Duplicate characters in '" << inputString << "': ";
: Displays a message indicating the operation about to be performed.printDuplicateCharacters(inputString);
: Calls the function to print duplicate characters in the string.std::cout << std::endl;
: Outputs a newline character for better formatting.return 0;
: Indicates successful completion of the program.