C Program To Check Strings are Anagram or not ?
C Program To Check Strings are Anagram or not
- Anagram are the words with same characters in jumbled form.
- To check whether two strings are anagrams or not, a string is assumed to consist of lower case.
- In two strings that contains same characters, only the order of characters can be different. It is called as anagram.
- For example, "LISTEN" - "SILENT" and "TRIANGLE" - "INTEGRAL" are anagram of each other.
Sample Code in C
#include <stdio.h>
int check_anagram(char [], char []);
int main()
{
char a[100], b[100];
printf("Enter a string:");
gets(a);
printf("/nEnter a string:");
gets(b);
if (check_anagram(a, b) == 1)
printf("/nThe strings are anagrams.\n");
else
printf("The strings aren't anagrams.\n");
return 0;
}
int check_anagram(char a[], char b[])
{
int first[26] = {0}, second[26] = {0}, c = 0;
// Calculating frequency of characters of first string
while (a[c] != '\0')
{
first[a[c]-'a']++;
c++;
}
c = 0;
while (b[c] != '\0')
{
second[b[c]-'a']++;
c++;
}
// Comparing frequency of characters
for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}
return 1;
}
Output
Enter a string: reactive
Enter a string: creative
The strings are anagrams.