C++ Program to find union and intersection of two strings


In this program, You will learn how to find union and intersection of two strings in C++.


First string is :abc

Second sting is :bcdef

Union of two string :abcdef

Intersection of two String :bc

Example: How to find union and intersection of two strings in C++.

#include<iostream>
#include<cstring>
using namespace std;

void findUnion(char str1[], char str2[]) {

    int f, l = 0;
    int i, j;

    char str3[100];
    int len1 = strlen(str1);
    int len2 = strlen(str2);

    while (str1[l] != '\0') {
        str3[l] = str1[l];
        l++;
    }

    for (i = 0; i < len2; i++) {
        f = 0;
        for (j = 0; j < len1; j++) {
            if (str2[i] == str1[j]) {
                f = 1;
            }
        }
        if (f == 0) {
            str3[l] = str2[i];
            l++;
        }
    }
    str3[l] = '\0';
    cout << "Union of Two Strings:" << str3;
}

void findIntersection(char str1[], char str2[]) {

    int i, j, k = 0;
    char str3[100];

    int len1 = strlen(str1);
    int len2 = strlen(str2);

    for (i = 0; i < len1; i++) {
        for (j = 0; j < len2; j++) {
            if (str1[i] == str2[j]) {
                str3[k] = str1[i];
                k++;
            }
        }
    }
    str3[k] = '\0';
    cout << "\nIntersection of Two Strings:" << str3;
}

int main() {

    char str1[100];
    char str2[100];
    char str3[100];

    int len1, len2, l = 0;
    int i, j, f;

    cout << "Enter First String:";
    cin.getline(str1, 100);

    cout << "Enter Second String:";
    cin.getline(str2, 100);

    findUnion(str1, str2);
    findIntersection(str1, str2);

    return 0;
}

Output:

Enter First String:abcd
Enter Second String:bcd
Union of Two Strings:abcd
Intersection of Two Strings:bcd