|
| 1 | +#include <stdio.h> |
| 2 | +#include <string.h> |
| 3 | +#include <stdlib.h> |
| 4 | + |
| 5 | +int checkAnagram(char *str1, char *str2); |
| 6 | + |
| 7 | +int main() |
| 8 | +{ |
| 9 | + char str1[100], str2[100]; |
| 10 | + |
| 11 | + printf("Function : whether two given strings are anagram :"); |
| 12 | + printf("\nExample : pears and spare, stone and tones :"); |
| 13 | + |
| 14 | + printf(" Input the first String : "); |
| 15 | + fgets(str1, sizeof str1, stdin); |
| 16 | + printf(" Input the second String : "); |
| 17 | + fgets(str2, sizeof str2, stdin); |
| 18 | + |
| 19 | + if(checkAnagram(str1, str2) == 1) |
| 20 | + { |
| 21 | + str1[strlen(str1)-1] = '\0'; |
| 22 | + str2[strlen(str2)-1] = '\0'; |
| 23 | + printf(" %s and %s are Anagram.\n\n",str1,str2); |
| 24 | + } |
| 25 | + else |
| 26 | + { |
| 27 | + str1[strlen(str1)-1] = '\0'; |
| 28 | + str2[strlen(str2)-1] = '\0'; |
| 29 | + printf(" %s and %s are not Anagram.\n\n",str1,str2); |
| 30 | + } |
| 31 | + return 0; |
| 32 | +} |
| 33 | + |
| 34 | + |
| 35 | +//Function to check whether two passed strings are anagram or not |
| 36 | + |
| 37 | +int checkAnagram(char *str1, char *str2) |
| 38 | +{ |
| 39 | + int str1ChrCtr[256] = {0}, str2ChrCtr[256] = {0}; |
| 40 | + int ctr; |
| 41 | + |
| 42 | + /* check the length of equality of Two Strings */ |
| 43 | + |
| 44 | + if(strlen(str1) != strlen(str2)) |
| 45 | + { |
| 46 | + return 0; |
| 47 | + } |
| 48 | + |
| 49 | + //count frequency of characters in str1 |
| 50 | + |
| 51 | + for(ctr = 0; str1[ctr] != '\0'; ctr++) |
| 52 | + { |
| 53 | + str1ChrCtr[str1[ctr]]++; |
| 54 | + } |
| 55 | + |
| 56 | + //count frequency of characters in str2 |
| 57 | + |
| 58 | + for(ctr = 0; str2[ctr] != '\0'; ctr++) |
| 59 | + { |
| 60 | + str2ChrCtr[str2[ctr]]++; |
| 61 | + } |
| 62 | + |
| 63 | + //compare character counts of both strings |
| 64 | + |
| 65 | + for(ctr = 0; ctr < 256; ctr++) |
| 66 | + { |
| 67 | + if(str1ChrCtr[ctr] != str2ChrCtr[ctr]) |
| 68 | + return 0; |
| 69 | + } |
| 70 | + return 1; |
| 71 | +} |
0 commit comments