C Program Anagrams

How to write a C Program Anagrams in C Programming Language ?

Considering a string will only contain lower-case alphabets. It can also be done for uppercase letters , digits , special characters etc.

Solution:

  1. #include<stdio.h>
  2. #include<stdbool.h>
  3. #include<string.h>
  4. bool isAnagram(char *str1,char *str2)
  5. {
  6.     int alphabetCount[26] = {0};
  7.     int i = 0;
  8.    
  9.     if(strlen(str1) != strlen(str2))
  10.         return false;
  11.    
  12.     for(i=0;str1[i]!='\0';++i)
  13.     {
  14.         ++alphabetCount[str1[i]-'a'];
  15.         --alphabetCount[str2[i]-'a'];
  16.     }
  17.    
  18.     for(i=0;i<26;++i)
  19.     {
  20.         if(alphabetCount[i])
  21.             return false;
  22.     }
  23.    
  24.     return true;
  25. }
  26.  
  27. int main(void)
  28. {
  29.    char string1[1001],string2[1001];
  30.    
  31.    /*
  32.      considering a string will only contain lower-case alphabets
  33.     It can also be done for uppercase letters , digits , special characters etc.
  34.     */
  35.    
  36.    gets(string1);
  37.    gets(string2);
  38.    
  39.    if(isAnagram(string1,string2))
  40.        printf("yes");
  41.    else
  42.        printf("no");
  43.    
  44.     return 0;
  45. }


Learn More :