C Program to check anagram by checking frequency
Program
#include<stdio.h>
int check_anagram(char strOne[], char strTwo[])
{
int freqOne[26] = {0}, freqTwo[26] = {0}, i = 0, j= 0;
while(strOne[i] != '\0')
{
freqOne[strOne[i] - 'a']++;
i++;
}
i = 0;
while(strTwo[i] != '\0')
{
freqTwo[strTwo[i] - 'a']++;
i++;
}
for(i = 0; i < 26; i++)
{
if(freqOne[i] != freqTwo[i])
return 0;
}
return 1;
}
void main()
{
char strOne[100], strTwo[100];
printf("Enter string 1:\t");
scanf("%s", strOne);
printf("Enter string 2:\t");
scanf("%s", strTwo);
if(check_anagram(strOne, strTwo) == 1)
{
printf("The strings are anagrams\n");
}
else
{
printf("The strings are not anagrams\n");
}
}
Output 1
$ gcc anagram-by-checking-frequency.c
$ ./a.out
Enter string 1: silent
Enter string 2: listen
The strings are anagrams
Output 2
$ gcc anagram-by-checking-frequency.c
$ ./a.out
Enter string 1: hello
Enter string 2: world
The strings are not anagrams