87.4k views
0 votes
Write a test program that prompts the user to enter two strings and, if they are anagrams, displays is an anagram; otherwise, it displays is not an anagram

User PPartisan
by
5.1k points

1 Answer

3 votes

Answer:-Following is the program for the checking if 2 strings are anagram in c++:-

#include<bits/stdc++.h>

using namespace std;

int main()

{

string ana1,ana2;//declaring two strings.

int an1[256]={},an2[256]={};//declare two count arrays of size 256 an1 and an2.

bool test=true;//taking a bool variable test = true for displaying the result..

cout<<"Enter both the strings"<<endl;

cin>>ana1>>ana2;//prompting the strings..

for(int i=0;ana1[i]&ana2[i];i++) // iterating over both the strings.

{

an1[ana1[i]]++;//increasing the count of the characters as per their ascii values in count array an1.

an2[ana2[i]]++;//increasing the count of the characters as per their ascii values in count array an2.

}

for(int i=0;i<256;i++)//iterating over the count arrays..

{

if(an1[i]!=an2[i])//condition for not anagram.

{

cout<<"not an anagram"<<endl;

test=false;//making test false..

break;//coming out of the loop.

}

}

if(test)//if test is true only then printing..

cout<<"is an anagram"<<endl;

return 0;

}

Explanation:-

A string is said to be an anagram string of other string if it has same characters but in different order.

for example:-

string 1="raman"

string 2="manar"

string 2 is an anagram of string 1.

User Sard
by
6.1k points