|
| 1 | +// C++ program to check if the strings are anagrams |
| 2 | + |
| 3 | +#include <bits/stdc++.h> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +// function to check whether two strings are anagram of each other |
| 7 | +bool areAnagram(string str1, string str2) |
| 8 | +{ |
| 9 | +// Get lengths of both strings |
| 10 | +int n1 = str1.length(); |
| 11 | +int n2 = str2.length(); |
| 12 | + |
| 13 | +// If length of both strings is not same, then they |
| 14 | +// cannot be anagram |
| 15 | +if (n1 != n2) |
| 16 | +return false; |
| 17 | + |
| 18 | +// Sort both the strings |
| 19 | +sort(str1.begin(), str1.end()); |
| 20 | +sort(str2.begin(), str2.end()); |
| 21 | + |
| 22 | +// Compare sorted strings |
| 23 | +for (int i = 0; i < n1; i++) |
| 24 | +if (str1[i] != str2[i]) |
| 25 | +return false; |
| 26 | + |
| 27 | +return true; |
| 28 | +} |
| 29 | + |
| 30 | +int main() |
| 31 | +{ |
| 32 | +string str1; |
| 33 | +string str2; |
| 34 | +cout << "\nInput the strings : "; |
| 35 | +cin >> str1 >> str2; |
| 36 | +if (areAnagram(str1, str2)) |
| 37 | +cout << "The two strings are anagram of each other"; |
| 38 | +else |
| 39 | +cout << "The two strings are not anagram of each other"; |
| 40 | + |
| 41 | +return 0; |
| 42 | +} |
0 commit comments