在C ++中按字母顺序打印两个字符串的公共字符

在这个编程问题中,我们给了两个字符串。并且我们必须找到字符串中两个字符串中所有共同的字符,并且必须按字母顺序打印这些共同的字符。如果没有出现普通字母,则打印找到“ NO COMMON CHARACTERS”。假定该字符串不包含所有小写字母。

让我们举个例子-

Input : string1 : adsfhslf
   string2 : fsrakf
Output : affs

说明-在两个字符串之间有a,f,s。因此,词典输出为“ afs”。

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

说明-没有字符是共同的。

要解决此问题,我们需要在字符串中找到常用字符。输出将是这些字符串的字典顺序。

算法

解决这个问题的算法是-

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.

示例

让我们基于此算法创建一个程序来说明工作原理-

#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;
}

输出结果

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