C++ program to find uncommon characters in two given strings

C++Server Side ProgrammingProgramming

In this article, we will be discussing a program to find out the uncommon characters during comparison of two different given strings.

As we know, strings are nothing but an array of characters. Therefore, for comparison we would be traversing through the characters of one string and simultaneously checking if that element exists in the other string.

If we let the first string be A and the second string B.Then it would give us A - B. Similarly we can calculate B - A.

Combining both of these results we would get

( A - B ) ∪ ( B - A )

i.e the uncommon elements among both the strings.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int len1 = 5, len2 = 4;
   char str1[len1] = "afbde", str2[len2] = "wabq";
   cout << "Uncommon Elements :" <<endl;
   //loop to calculate str1- str2
   for(int i = 0; i < len1; i++) {
      for(int j = 0; j < len2; j++) {
         if(str1[i] == str2[j])
            break;
         //when the end of string is reached
         else if(j == len2-1) {
            cout << str1[i] << endl;
            break;
         }
      }
   }
   //loop to calculate str2- str1
   for(int i = 0; i < len2; i++) {
      for(int j = 0; j < len1; j++) {
         if(str2[i] == str1[j])
            break;
         else if(j == len1-1) {
            cout << str2[i] << endl;
            break;
         }
      }
   }
   return 0;
}

Output

Uncommon Elements :
f
d
e
w
q
raja
Published on 03-Oct-2019 14:40:50
Advertisements