Print common characters of two Strings in alphabetical order in C++


In this programming problem, we are given two strings. And we have to find all the characters of the string that are common in both the string and we have to print these common characters in alphabetical order. And print ‘NO COMMON CHARACTERS ’ found if no common letters arise. Given that the string does not contain all lower case alphabets.

Let’s take an example −

Input : string1 : adsfhslf
   string2 : fsrakf
Output : affs

Explanation − Between the two strings there are a, f, s. Hence the lexicographical output is ‘afs’.

Input : string1 : abcde
   string2 : glhyte
Output : No common characters

Explanation − There are no characters are in common.

To solve this problem, we need to find common characters in the string. And the output will be the lexicographical order of these string.

Algorithm

Algorithm to solve this problem is −

Step 1 : Create two arrays a1[] and a2[] of size 26 each for counting the number of alphabets in the strings string1 and string2.
Step 2 : traverse a1[] and a2[]. and in sequence print all those numbers that have values in the array.

Example

Let's create a program based on this algorithm to illustrate the working −

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int main(){
   string string1 = "adjfrdggs";
   string string2 = "gktressd";
   cout<<"The strings are "<<string1<<" and "<<string2;
   cout<<"\nThe common characters are : ";
   int a1[26] = {0};
   int a2[26] = {0};
   int i , j;
   char ch;
   char ch1 = 'a';
   int k = (int)ch1, m;
   for(i = 0 ; i < string1.length() ; i++){
      a1[(int)string1[i] - k]++;
   }
   for(i = 0 ; i < string2.length() ; i++){
      a2[(int)string2[i] - k]++;
   }
   for(i = 0 ; i < 26 ; i++){
      if (a1[i] != 0 and a2[i] != 0){
         for(j = 0 ; j < min(a1[i] , a2[i]) ; j++){
            m = k + i;
            ch = (char)(k + i);
            cout << ch;
         }
      }
   }
   return 0;
}

Output

The strings are adjfrdggs and gktressd
The common characters are : dgrs

Updated on: 03-Jan-2020

529 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements