How to get intersection of two strings in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <unordered_set>

std::string getIntersection(const std::string& str1, const std::string& str2) {
    std::unordered_set<char> set1(str1.begin(), str1.end());
    std::unordered_set<char> intersection;

    for (char ch : str2) {
        if (set1.count(ch)) {
            intersection.insert(ch);
        }
    }

    // Build the result string
    std::string result;
    for (char ch : intersection) {
        result += ch;
    }

    return result;
}

int main() {
    std::string str1 = "php";
    std::string str2 = "python";

    std::string intersection = getIntersection(str1, str2);

    std::cout << "Intersection: " << intersection << std::endl;
}

 
 
/*
run:

Intersection: hp
 
*/

 



answered Jul 6, 2025 by avibootz
...