# Count common characters in two strings in C++

C++Server Side ProgrammingProgramming

We are given with the two strings let’s say str1 and str2 and the task is to find the count of common characters in two strings i.e. if str1[i] = str[j], then they will be considered as a pair and count will increased to 1 and if str1[i]!=str2[j] then they willn’t be considered as a pair and count willn’t increase to 1.

## For Example

Input − str1 = “hello”
str2 = “heoo”
Output − count is: 3

Explanation − str1[0] = str2[0] i.e. h ; str1[1] = str2[1] i.e. e ; str1[2]!=str2[2] i.e. l and o; str1[3]=str2[3] i.e. o. So, the pairs with similar letters are 3 and 1 pair containing different letters.

Input − str1 = “point”
str2 = “print”
Output − count is: 4

Explanation − str1[0] = str2[0] i.e. p ; str1[1] != str2[1] i.e. o and r ; str1[2] =str2[2] i.e. i; str1[3]=str2[3] i.e. n; str1[4]=str2[4] i.e. t. So, the pairs with similar letters are 4 and 1 pair containing different letters.

## Approach used in the below program is as follows

• Input the two strings str1 and str2

• Calculate the size of both the strings using length() function that will return an integer value as per the number of letters in the string including the spaces.

• Initially, Initialize the frequency of characters in both the string with 0.

• Now, for updating the frequency of str1 apply “f1[str1[i] - 'a']++” that will increase the frequency with every iteration and apply the same process with str2

• For calculating the count of pairs apply min() function for f1 and f2.

• Display the result

## Example

Live Demo

#include <iostream>
using namespace std;
// Function to count the valid indices pairs
int pairs(string str1, int size1, string str2, int size2){
// f1 and f2 for frequencies of characters
// of string str1 and str2
int f1[26] = { 0 };
int f2[26] = { 0 };
// 'c' To count the valid pairs
int i, c = 0;
//updating the frequencies of str1 and st2
for (i = 0; i < size1; i++){
f1[str1[i] - 'a']++;
}
for (i = 0; i < size2; i++){
f2[str2[i] - 'a']++;
}
// Find the count of valid pairs
for (i = 0; i < 26; i++){
c += (min(f1[i], f2[i]));
}
return c;
}
// main function
int main(){
string str1 = "tutorialspoint", str2 = "codingground";
int size1 = str1.length(), size2 = str2.length();
cout<<”Total pairs with str1[i]=str2[j] are: ”;
cout << pairs(str1, size1, str2, size2);
return 0;
}

## Output

If we run the above code it will generate the following output −

Total pairs with str1[i]=str2[j] are − 6
Published on 15-May-2020 08:32:01