forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagram_checker.c
More file actions
63 lines (55 loc) · 1.55 KB
/
anagram_checker.c
File metadata and controls
63 lines (55 loc) · 1.55 KB
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
/*
anagram_checker.c
Check whether two input strings are anagrams of each other.
- Ignores non-alphanumeric characters and case.
- Uses a fixed 256-byte frequency table for simplicity.
Compile:
gcc -o anagram_checker anagram_checker.c
Usage:
./anagram_checker
Enter first string: Silent
Enter second string: Listen
Result: Anagrams
This program is small, easy to read, and not present in the repo snippet you supplied.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void normalize_and_count(const char *s, int freq[256]) {
for (; *s; ++s) {
unsigned char c = (unsigned char)*s;
if (isalnum(c)) {
unsigned char lower = (unsigned char)tolower(c);
freq[lower]++;
}
}
}
int main(void) {
char a[1024], b[1024];
printf("Enter first string: ");
if (!fgets(a, sizeof(a), stdin)) return 1;
printf("Enter second string: ");
if (!fgets(b, sizeof(b), stdin)) return 1;
// Remove trailing newlines
a[strcspn(a, "\n")] = '\0';
b[strcspn(b, "\n")] = '\0';
int freq[256] = {0};
normalize_and_count(a, freq);
// decrement with second string
for (const char *s = b; *s; ++s) {
unsigned char c = (unsigned char)*s;
if (isalnum(c)) {
unsigned char lower = (unsigned char)tolower(c);
freq[lower]--;
}
}
// check all zero
for (int i = 0; i < 256; ++i) {
if (freq[i] != 0) {
printf("Result: Not anagrams\n");
return 0;
}
}
printf("Result: Anagrams\n");
return 0;
}