Ask Question

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

+2
Answers (1)
  1. 15 April, 21:04
    0
    C+ + program for the checking if 2 strings are anagram : -

    #include

    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"<
    test=false; //making test false ...

    break; //coming out of the loop.

    }

    }

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

    cout<<"is an anagram"<
    }

    int main ()

    {

    string s1, s2; //declaring two strings.

    cout<<"Enter both the strings"<
    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"<
    return 0;

    }

    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.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a function that checks whether two words are anagrams. Two words are anagrams if they contain the same letters. For example, silent ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers