Two strings are said to be anagram of each other if letters of one string can be rearranged to produce the other string.like “abccd” and “accbd” , both the strings are anagram of each other. here is c program to test whether two strings are anagram.

The implementation is a two step process.
1. Sort the strings letters.
2. Compare both the strings, if both the strings are same, they are anagram of each other.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

/* compare function for qsort function */
int my_compare(const void* a,const void* b)
{
     const char* ia = (const char*)a;
     const char* ib = (const char*)b;
     return (*ia - *ib);
}

int main()
{
   char inp_1[]="abccd";
   char inp_2[]="accbd";

   int size_of_str_1 = strlen(inp_1);
   int size_of_str_2 = strlen(inp_2);

   if(size_of_str_1 != size_of_str_2)
   {
       printf("both strings are not anagram\n");
       return 0;
   }
      /*do quick sort*/
      qsort(inp_1,size_of_str_1,sizeof(char),my_compare);
      qsort(inp_2,size_of_str_2,sizeof(char),my_compare);

     /* now compare the sorted strings*/
     int i=0;
     for(i;i<size_of_str_1;i++)
     {
        if(inp_1[i] != inp_2[i])
        {
             printf("both strings are not anagram\n");
             return 0;
        }
     }

      printf("both strings are anagram\n");
return 0;
}



Related Contents to follow