Programming Examples
C program to check whether the two strings anagram of each other or not.
Write a program to check whether the two strings anagram of each other or not.
Anagram :- When two strings contain the same characters irrespective of the order of occurrence then such strings are known as Anagram.
For Example :-
String1 = LISTEN
String2 = SILENT
So as we can see that both strings have same characters, only the order of characters is different so this is an Anagram.
Solution
#include<stdio.h>
int check_anagram(char [], char []);
int main()
{
char str1[1000]="listen", str2[1000]="silent";
if (check_anagram(str1, str2))
printf("The two strings are anagram of each other\n");
else
printf("The two strings are not anagram of each other\n");
return 0;
}
int check_anagram(char str1[], char str2[])
{
int first[26] = {0}, second[26] = {0}, third=0;
// Calculating frequency of characters of the first string
while (str1[third] != '\0') {
first[str1[third]-'a']++;
third++;
}
third = 0;
while (str2[third] != '\0') {
second[str2[third]-'a']++;
third++;
}
// Comparing the frequency of characters
for (third = 0; third < 26; third++)
if (first[third] != second[third])
return 0;
return 1;
}
Output
The two strings are anagram of each other