vendredi 8 mai 2015

Anagrams of two strings

Write C a program to find whether the 2 given strings are anagrams or not.

Input consists of 2 string. Assume that all characters in the string are lowercase letters or spaces and the maximum length of the string is 100.

Sample Input and Output 1: Enter the first string anitha Enter the second string amphisoft anitha and amphisoft are not anagrams

Sample Input and Output 2: Enter the first string the eyes Enter the second string they see the eyes and they see are anagrams

Sample Input and Output 3: Enter the first string dormitory Enter the second string dirty room dormitory and dirty room are anagrams

#include <stdio.h>

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

int main()
{
   char a[100], b[100];
   int flag;

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

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

   flag = check_anagram(a, b);

   if (flag == 1)
      printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
   else
      printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);

   return 0;
}

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

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

   c = 0;

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

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

   return 1;
}

I write the code but it was working only for first one input/output but second and third one input it was not working.

Aucun commentaire:

Enregistrer un commentaire