How to get intersection of two strings in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#define MAX_RESULT_SIZE 64

// Check if character is already in array
bool contains(char* arr, int size, char ch) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == ch) {
            return true;
        }
    }
    
    return false;
}

// Get the intersection of characters from two strings
int getIntersection(const char* str1, const char* str2, char* result) {
    int resultSize = 0;

    for (int i = 0; str2[i] != '\0'; i++) {
        char ch = str2[i];

        if (strchr(str1, ch) && !contains(result, resultSize, ch)) {
            result[resultSize++] = ch;
        }
    }

    result[resultSize] = '\0'; // Null-terminate the result string
    
    return resultSize;
}

int main() {
    const char* str1 = "php";
    const char* str2 = "python";
    char intersection[MAX_RESULT_SIZE];

    getIntersection(str1, str2, intersection);

    printf("Intersection: %s\n", intersection);

    return 0;
}



/*
run:

Intersection: ph

*/

 



answered Jul 6, 2025 by avibootz
...