C++ program to check whether two strings have same character or not

Hello Friends, Today we are going to learn how to check whether two strings have the same character or not, the order of characters can be different. First, we will see understand the problem, and then we will see the implementation part. So, Let’s start with an example.

a= rahul    ,    b = harul      c= rrahul

We can see that a and b have the same character and the order of character may be different so they are satisfying our condition whereas a and c are not satisfying.

Now, let’s see how effectively we can implement this.

C++ code for checking whether strings have the same characters or not

#include <bits/stdc++.h>
using namespace std;
bool ischeck(string a, string b);
int main()
    string a, b;
    cin >> a >> b;       // suppose input is a = rahul  b= harul 
    if(ischeck(a, b)) 
      cout << "True" << endl;
       cout << "False" << endl;
bool ischeck(string a, string b)
     map<char, int> occur1;
     for(int i=0;i<a.length();i++)
     map<char, int> occur2;
     for(int i=0;i<b.length();i++)
     if(occur1 == occur2)
         return true;
          return false;
Output: true

Understanding the Algorithm

This program is quite simple and easy to understand. First I created two maps of name occur1 and occur2 in which I am storing the frequency of characters of both strings separately. This code ” occur2[b[i]]++; ” will help you to store the frequency of each character and later on we can compare these two maps. If they are equal, it means both strings contain the same characters.

I hope you enjoyed this tutorial. Don’t stop learning and see our next tutorial.

Group all Anagrams together in C++

Leave a Reply

Your email address will not be published. Required fields are marked *