Find common characters in two string
Simple C program to find and print common characters in two strings. This program will find common character and will print them. This program will print common characters with frequency of character that are present in both strings.
For example if two strings are "programminhside" and "grammer" then output will be
Char Freq
'a' 1
'e' 1
'g' 1
'm' 2
'r' 2
C Program:
For example if two strings are "programminhside" and "grammer" then output will be
Char Freq
'a' 1
'e' 1
'g' 1
'm' 2
'r' 2
C Program:
#include<stdio.h> #include<stdlib.h> #define SIZE 256 int *CharCountArray(char *str) { /*Create a array to store frequency of character //value at index i = characters with ascii value i */ int *count=(int*)calloc(sizeof(int),SIZE); int i=0; /* store frequency by traversing string //increase frequency by one when a character is found // in string */ while(*(str+i)) { count[*(str+i)]++; i++; } return count; } void CommonChar(char *str1, char *str2) { /*Two count array for both string */ int *count1=CharCountArray(str1); int *count2=CharCountArray(str2); int i=0,flag=0;; printf("Common characters: \n"); while(i<256) { /*compare both arrays value at index i and //print lower value because lower value is //common in both array. suppose count1[99]= 4; //and count2[99]=3 then common characters are 3 */ if(count1[i]!=0&&count2[i]!=0) { if(count1[i]<count2[i]) { printf("%c = %d\n",i,count1[i]); flag=1; } else { printf("%c = %d\n",i,count2[i]); flag=1; } } i++; } if(flag==0) { printf("No common character\n"); } } int main() { char str1[100], str2[100]; printf("Enter first string: "); scanf("%s",str1); printf("Enter second string: "); scanf("%s",str2); CommonChar(str1,str2); return 0; }