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:

  1. Header inclusion:

    • #include <iostream>: Required for input/output operations.
    • #include <unordered_map>: Included to use the std::unordered_map container.
  2. 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.
  3. 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.
  4. main() function:

    • std::string inputString = "hello world";: Declares a string variable inputString 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.