150k views
3 votes
Write a function that checks whether two words are anagrams. Two words are anagrams if they contain the same letters. For example, silent and listen are anagrams. The header of the function is: def isAnagram(s1, s2): (Hint: Obtain two lists for the two strings. Sort the lists and check if two lists are identical.)

User Vikki
by
4.9k points

1 Answer

7 votes

C++ program for the checking if 2 strings are anagram :-

#include<bits/stdc++.h>

using namespace std;

void isAnagram(string s1,string s2) //defining function

{

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..

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

{

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

an2[s2[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;

}

int main()

{

string s1,s2;//declaring two strings.

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

cin>>s1>>s2;//prompting the strings..

if(s1.length()==s2.length()) //checking whether the lengths of string is same or not

isAnagram(s1,s2); //calling function

else

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

return 0;

}

Step-by-step explanation

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

for example:-

string 1="silent"

string 2="listen"

string 2 is an anagram of string 1.

void isAnagram(string s1,string s2) - This is the function having name isAnagram of void return type having parameters s1 and s2.

User NateJ
by
5.5k points