C program to find whether string is an anagram or not.

 

01 #include <stdio.h>
02
03 int anagram(char [], char []);
04
05 int main()
06 {
07 char str1[50], str2[50];
08 int check;
09
10 printf("Enter first string : ");
11 gets(str1);
12
13 printf("Enter second string : ");
14 gets(str2);
15 check = anagram(str1, str2);
16
17 if (check == 1)
18 printf(""%s" and "%s" are Anagrams.", str1, str2);
19 else
20 printf(""%s" and "%s" are not Anagrams.", str1, str2);
21
22 }
23
24 int anagram(char s1[], char s2[])
25 {
26 int first_str[256] = {0}; // initialized by 0
27 int second_str[256] = {0};
28 /*
29 first_str and second_str are used for counting character occurrence.
30 size 256 >> (possible character symbols).
31 */
32
33 int i = 0;
34
35 while (s1[i] != '')
36 {
37 first_str[s1[i]]++; //increament occurrence count
38 i++;
39 }
40
41 i = 0;
42
43 while (s2[i] != '')
44 {
45 second_str[s2[i]]++; //increament occurrence count
46 i++;
47 }
48
49 for (i = 0; i < 256; i++)
50 {
51 if (first_str[i] != second_str[i])
52 return 0;
53 }
54 return 1;
55 }
 
 OUTPUT :

1st RUN:

Enter first string : cola
Enter second string : coal

"cola" and "coal" are Anagrams.


2nd RUN:

Enter first string : hey
Enter second string : yah

"hey" and "yah" are not Anagrams.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *