Find uncommon characters of the two strings in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to find distinct characters from the given two strings. Let's see an example.

Input 

string_one = "tutorialspoint"
string_two = "tutorialsworld"

Output

d n p w

We are going to use hashing to solve the problem. It's more efficient than writing two nested loop

Let's see the steps to solve the program.

  • Initialize the two strings with some random values.

  • Initialize a map as map<char, int> chars.

  • Iterate over the first string and insert each character into map with value 1.

  • Now, iterate over the second string.

    • Check whether the character is already present or not.

    • If present, assign 0 to it.

    • If not present insert the character with value 1.

  • Iterate over the map and print characters with value 1.

Example

See the code below.

 Live Demo

#include <bits/stdc++.h>
#include <map>
using namespace std;
void findDistinctCharacters(string one, string two){
   // initializing char presence in string
   map<char, int> chars;
   // iterating over the first string
   for (int i = 0; i < one.size(); ++i){
      // inserting every character into map
      chars.insert({one[i], 1});
   }
   // iterating over the second string
   for (int i = 0; i < two.size(); ++i){
      // checking whether the current char in string or not
      if (chars.count(two[i])) {
         // assigning 0 for common chars
         chars.find(two[i])->second = 0;
      }
      else {
         // insering new chars
         chars.insert({two[i], 1});
      }
   }
   // printing the distinct characters
   for (auto item: chars){
      // checking the presence
      if (item.second == 1) {
         // printing the distinct char
         cout << item.first << " ";
      }
   }
}
int main(){
   string one = "tutorialspoint";
   string two = "tutorialsworld";
   findDistinctCharacters(one, two);
   return 0;
}

Output

If you run the above code, you will get the following result.

d n p w

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 10:39:41
Advertisements