This is a C++ Program to Find if Two Strings are Anagrams.
The program takes two strings and checks if they are anagrams. An anagram is a phrase formed by rearranging the letters of a different phrase.
1. The program takes two strings.
2. Using a function, the two strings are sorted and checked if they are anagrams.
3. The result is printed.
4. Exit.
Here is the source code of C++ Program to Find if Two Strings are Anagrams. The program output is shown below.
#include <iostream>
using namespace std;
int anagram(char str1[], char str2[])
{
int i, flag = 0, x[26] = {0}, y[26] = {0};
for(i = 0; str1[i] != '\0'; i++)
x[str1[i] - 'a']++;
for(i = 0; str2[i] != '\0'; i++)
y[str2[i] - 'a']++;
for (i = 0; i < 26; i++)
{
if (x[i] != y[i])
flag = 1;
}
if (flag == 1)
cout << "Entered strings are not anagrams.";
else
cout << "Entered strings are anagrams.";
}
int main ()
{
char str1[50], str2[50];
int flag;
cout << "Enter string 1 : ";
gets(str1);
cout << "Enter string 2 : ";
gets(str2);
anagram(str1, str2);
return 0;
}
1. The user is asked to enter two strings and stored in ‘str1’ and ‘str2’.
2. The function ‘anagram()’ is called, passing the two strings.
3. Within the function, the frequency of each character is calculated using a for loop for both the strings.
4. Again using a for loop, frequency of both the strings is compared.
5. If they are not equal, the strings are not anagrams, else they are.
6. The result is then printed.
Case 1 : Enter string 1 : creative Enter string 2 : reactive Entered strings are anagrams. Case 2 : Enter string 1 : mom10 Enter string 2 : 10dad Entered strings are not anagrams. Case 3 : Enter string 1 : 24 lessons Enter string 2 : son24 less Entered strings are anagrams.
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Check Programming Books
- Apply for Computer Science Internship
- Check Computer Science Books
- Check C++ Books
- Practice Computer Science MCQs