RUN

# Program to check if two strings are anagrams

Written By -

Anagrams are the strings that have the same letters but the letters are in different orders.

For a better understanding look at the following examples below:

eat, tea, ate
ant, tan
gold ring , long grid
chairman, chair man

Thus, from the above examples, we can say that

1. Total Number of letters are same.
2. String length need not be same.

Logic:

We will use our first observation as the main idea. We take an array of size 26 to keep a count of each letter of the string. For example, count[0] will contain the number of ‘a’ in the string.

Algorithm:

1. Take two strings as input.
2. Initialize two arrays (one for each string) of size 26, and initialize them to 0.
3. Run a loop and traverse the string.
4. Next, with the ascii code of each character. We will determine its position by subtracting 97 from it.
5. Increase the count at that index (of count array) by 1.
6. Perform the same process for the second string.
7. Next, compare the value at each index of count1[] and count2[].
8. If they match we can say that the string are anagrams else, they are not.

Code:

``````#include <iostream>
#include<string>
using namespace std;

int isanagram(string str1,string str2)
{
int count1[26] = {0}, count2[26] = {0}, ascii, i = 0;
while (str1[i] != '\0')         //counting all alphabets in string 1
{
ascii=str1[i]-97;	//taking each character's ascii value and feeding it into the count array
count1[ascii]+=1;	//taking into assumption that the string is made of lower case chars only.
i++;
}
i = 0;
while (str2[i] != '\0')              //counting all alphabets in string 2
{
ascii=str2[i]-97;
count2[ascii]+=1;
i++;
}
for (i = 0; i < 26; i++) //comparing the count of chars in both strings
{
if (count1[i] != count2[i])
return 0;
}
return 1;
}

int main()
{

string str1,str2;
cout<<"Enter string 1\n";
getline(cin,str1);
cout<<"Enter String 2:\n";
getline(cin,str2);

if (isanagram(str1, str2)) //calling the anagram checking method
printf("The strings are anagrams\n");
else
printf("The strings are not anagrams\n");
return 0;
}``````

Output:

Optimistic case:

``````
Enter string 1anagram
Enter String 2:nag a ram
The strings are anagrams
``````

Pessimistic case:

``````
Enter string 1hello
Enter String 2:world
The strings are not anagrams
``````

Report Error/ Suggestion

Related Posts:

Tutorials

Examples

Online Compilers

Interview Questions

Recent Articles

CopyRight © 2020

CopyRight © 2020