How to get the number of characters that two strings have in common in C++

2 Answers

0 votes
#include <iostream>
#include <unordered_map>
#include <algorithm>

int commonCharacters(const std::string& str1, const std::string& str2) {
    std::unordered_map<char, int> charCount;
    int commonCount = 0;

    // Count characters in the first string
    for (char ch : str1) {
        charCount[ch]++;
    }

    // Check characters in the second string
    for (char ch : str2) {
        if (charCount[ch] > 0) {
            commonCount++;
            charCount[ch]--; // Decrement count to avoid double counting
        }
    }

    return commonCount;
}

int main() {
    std::string str1 = "abcdefg";
    std::string str2 = "xayzgoe";

    int result = commonCharacters(str1, str2);
    std::cout << "Number of common characters: " << result << std::endl;
}


  
/*
run:
 
Number of common characters: 3
  
*/

 



answered Mar 19, 2025 by avibootz
0 votes
#include <iostream>
#include <unordered_set>
#include <string>

int commonCharactersCount(const std::string& str1, const std::string& str2) {
    // Create sets for characters in each string
    std::unordered_set<char> set1(str1.begin(), str1.end());
    std::unordered_set<char> set2(str2.begin(), str2.end());

    // Count the common characters
    int count = 0;
    for (char c : set1) {
        if (set2.find(c) != set2.end()) {
            count++;
        }
    }

    return count;
}

int main() {
    std::string str1 = "abcdefg";
    std::string str2 = "xayzgoe";

    int count = commonCharactersCount(str1, str2);
    
    std::cout << count << std::endl; 
}


  
/*
run:
 
3
  
*/

 



answered Mar 20, 2025 by avibootz
...