Sunday, March 16, 2014

Check Anagram in C

Share Post:
#include <stdio.h>
#include<conio.h>
int check_anagram(char [], char []);

int main()
{
   char s1[110], s2[110];
   int cond;

   printf("Enter first string\n");
   gets(s1);

   printf("Enter second string\n");
   gets(s2);


   cond = check_anagram(s1, s2);

   if (cond == 1)
      printf("\"%s\" & \"%s\" are anagrams.\n", s1, s2);
   else
      printf("\"%s\" & \"%s\" aren't anagrams.\n", s1, s2);

   return 0;
}

int check_anagram(char a[], char b[])
{
   int first[26] = {0}, second[26] = {0}, i = 0;

   while (a[i] != '\0')
   {
      first[a[i]-'a']++;
      i++;
   }

   i = 0;

   while (b[i] != '\0')
   {
      second[b[i]-'a']++;
      i++;
   }

   for (i = 0; i < 26; i++)
   {
      if (first[i] != second[i])
         return 0;
   }

   return 1;
}

0 comments:

Post a Comment