Count Common characters in two strings
Given two strings, count total number of common characters. For example if two strings are "coder" and "side" then common characters are 2 ( 'd' and 'e' ). If strings are "Programming" and "Side" then common character is 'i'. If strings are "aabbcc" and "aabcc" then common characters are 5 ( 2'a', 1'b', 2'c' ).
Simple method is create a character count array for string 1 and count frequency of each characters in string and then count common characters in string 2. If strings are "aabbccab" and "aabd". And a variable to count common characters is common_char = 0.
count frequency of each character in string 1
count['a'] = 3;
count['b'] = 3;
count['c'] = 2;
Now find common characters in string 2.
str2[0] => count['a'] = 3; common_char = 1; count['a']--;
str2[1] => count['a'] = 2; common_char = 2; count['a']--;
str2[2] => count['b'] = 3; common_char = 3; count['b']--;
str2[3] => count['d'] = 0; common_char = 3; count['d'] (no change)
C Program:
Simple method is create a character count array for string 1 and count frequency of each characters in string and then count common characters in string 2. If strings are "aabbccab" and "aabd". And a variable to count common characters is common_char = 0.
count frequency of each character in string 1
count['a'] = 3;
count['b'] = 3;
count['c'] = 2;
Now find common characters in string 2.
str2[0] => count['a'] = 3; common_char = 1; count['a']--;
str2[1] => count['a'] = 2; common_char = 2; count['a']--;
str2[2] => count['b'] = 3; common_char = 3; count['b']--;
str2[3] => count['d'] = 0; common_char = 3; count['d'] (no change)
C Program:
/* Count common characters in two string */ #include<stdio.h> #include<stdlib.h> #define MAX 256 int *CountArray(char *str) { int *count=(int *)calloc(sizeof(int),MAX); int i;
/* Count frequency of each character in first string */
for(i=0;*(str+i);i++) { count[*(str+i)]++; } return count; } int CountCommonChar(char *str1, char *str2) { int *count=CountArray(str1); int i,count_char=0; for(i=0;*(str2+i);i++) { if(count[*(str2+i)]!=0) { count_char++; count[*(str2+i)]--; } } return count_char; } int main() { char str1[100],str2[100]; printf("Enter first string: "); scanf("%s",str1); printf("Enter second string: "); scanf("%s",str2); int n=CountCommonChar(str1,str2); printf("Common char = %d",n); return 0; }