C Program to check whether two strings are anagram

Before moving forward to write program to check whether two strings are anagram or not. We will discuss what actually anagrams are. Anagram is a form of word play in which letters of a word or phrase are rearranged in such a way that a new word or phrase is formed. Anagram is formed by using exactly the same letters of the original word but with a different arrangement.

For example :  example is “silent” which can be rearranged to “listen”. And THE EYES is an anagram of THEY SEE. One simple approach to check whether two strings are anagram or not is to find how many times characters appear in the strings and then comparing their corresponding counts.

#include <stdio.h> // Header files

int anagram(char [], char []);

int main()

{

char a[100], b[100];

int x;

printf(“Enter 1st string\n“);

gets(a);

printf(“Enter 2nd string\n“);

gets(b);

x = anagram(a, b); // Calling the Function

if (x == 1)

printf(“\”%s\” and \”%s\” are anagrams.\n“, a, b);

else

printf(“\”%s\” and \”%s\” are not anagrams.\n“, a, b);

return 0;

}

int anagram(char a[], char b[])

{

int string1[26] = {0}, string2[26] = {0}, c = 0;

while (a[c] != ‘\0‘)

{

string1[a[c]-‘a’]++;

c++;

}

c = 0;

while (b[c] != ‘\0‘)

{

string2[b[c]-‘a’]++;

c++;

}

for (c = 0; c < 26; c++)

{

if (string1[c] != string2[c])

return 0;

}

return 1;

}

Mohit Arora
Follow me