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