
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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