Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,404 questions

56,379 answers

573 users

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

1 Answer

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

int commonCharacters(char *str1, char *str2) {
    int count = 0;
    int freq1[256] = {0};
    int freq2[256] = {0};

    // Count frequency of each character in str1
    for (int i = 0; str1[i] != '\0'; i++) {
        freq1[(unsigned char)str1[i]]++;
    }

    // Count frequency of each character in str2
    for (int i = 0; str2[i] != '\0'; i++) {
        freq2[(unsigned char)str2[i]]++;
    }

    // Find common characters
    for (int i = 0; i < 256; i++) {
        if (freq1[i] > 0 && freq2[i] > 0) {
            count += (freq1[i] < freq2[i]) ? freq1[i] : freq2[i];
        }
    }

    return count;
}

int main() {
    char str1[] = "abcdefg";
    char str2[] = "xayzgoe";

    int result = commonCharacters(str1, str2);
    
    printf("Number of common characters: %d\n", result);
}



/*
run:

Number of common characters: 3

*/

 



answered Mar 19, 2025 by avibootz
...