C Online Compiler
Example: Anagram Check (Character Counting Method) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Anagram Check (Character Counting Method) #include <stdio.h> #include <string.h> #include <stdlib.h> // For EXIT_FAILURE and dynamic allocation if needed, not strictly for this version // Assuming ASCII character set for simplicity (0-255) #define MAX_CHARS 256 // Function to check if two strings are anagrams using character counting int areAnagramsCounting(char *str1, char *str2) { // Step 1: Declare a frequency array and initialize it to zeros int count[MAX_CHARS] = {0}; // Step 2: Get lengths of both strings int len1 = strlen(str1); int len2 = strlen(str2); // Step 3: If lengths are different, they cannot be anagrams if (len1 != len2) { return 0; // Not anagrams } // Step 4: For the first string, increment count for each character for (int i = 0; i < len1; i++) { count[(unsigned char)str1[i]]++; } // Step 5: For the second string, decrement count for each character for (int i = 0; i < len2; i++) { count[(unsigned char)str2[i]]--; } // Step 6: Check if all counts in the array are zero // If any count is non-zero, it means character frequencies don't match for (int i = 0; i < MAX_CHARS; i++) { if (count[i] != 0) { return 0; // Not anagrams } } // Step 7: If all counts are zero, they are anagrams return 1; } int main() { char str1[] = "anagram"; char str2[] = "nagaram"; char str3[] = "rat"; char str4[] = "car"; printf("Checking \"%s\" and \"%s\":\n", str1, str2); if (areAnagramsCounting(str1, str2)) { printf("They are anagrams.\n"); } else { printf("They are not anagrams.\n"); } printf("\nChecking \"%s\" and \"%s\":\n", str3, str4); if (areAnagramsCounting(str3, str4)) { printf("They are anagrams.\n"); } else { printf("They are not anagrams.\n"); } return 0; }
Output
Clear
ADVERTISEMENTS