C Online Compiler
Example: Anagram Check (Sorting Method) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Anagram Check (Sorting Method) #include <stdio.h> #include <string.h> #include <stdlib.h> // For qsort // Comparison function for qsort int compareChars(const void *a, const void *b) { return (*(char*)a - *(char*)b); } // Function to check if two strings are anagrams using sorting int areAnagramsSorting(char *str1, char *str2) { // Step 1: Get lengths of both strings int len1 = strlen(str1); int len2 = strlen(str2); // Step 2: If lengths are different, they cannot be anagrams if (len1 != len2) { return 0; // Not anagrams } // Step 3: Create copies of the strings to avoid modifying originals char *s1_copy = (char *)malloc(sizeof(char) * (len1 + 1)); char *s2_copy = (char *)malloc(sizeof(char) * (len2 + 1)); if (s1_copy == NULL || s2_copy == NULL) { perror("Memory allocation failed"); exit(EXIT_FAILURE); } strcpy(s1_copy, str1); strcpy(s2_copy, str2); // Step 4: Sort both copied strings qsort(s1_copy, len1, sizeof(char), compareChars); qsort(s2_copy, len2, sizeof(char), compareChars); // Step 5: Compare the sorted strings int result = strcmp(s1_copy, s2_copy) == 0; // Step 6: Free dynamically allocated memory free(s1_copy); free(s2_copy); return result; } int main() { char str1[] = "listen"; char str2[] = "silent"; char str3[] = "hello"; char str4[] = "world"; printf("Checking \"%s\" and \"%s\":\n", str1, str2); if (areAnagramsSorting(str1, str2)) { printf("They are anagrams.\n"); } else { printf("They are not anagrams.\n"); } printf("\nChecking \"%s\" and \"%s\":\n", str3, str4); if (areAnagramsSorting(str3, str4)) { printf("They are anagrams.\n"); } else { printf("They are not anagrams.\n"); } return 0; }
Output
Clear
ADVERTISEMENTS