Check if Two Strings are Anagrams in C
Introduction
This program checks if two strings are anagrams of each other. Two strings are considered anagrams if they contain the same characters with the same frequency, but possibly in a different order.
C Program
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/**
* Function to check if two strings are anagrams of each other.
*
* @param str1 The first string.
* @param str2 The second string.
* @return true if the strings are anagrams, false otherwise.
*/
bool areAnagrams(char *str1, char *str2) {
// If lengths of the strings are different, they cannot be anagrams
if (strlen(str1) != strlen(str2)) {
return false;
}
// Array to keep track of character counts
int charCount[256] = {0};
// Increment the count for each character in the first string
for (int i = 0; str1[i] != '\0'; i++) {
charCount[(unsigned char)str1[i]]++;
}
// Decrement the count for each character in the second string
for (int i = 0; str2[i] != '\0'; i++) {
charCount[(unsigned char)str2[i]]--;
}
// If all counts are zero, the strings are anagrams
for (int i = 0; i < 256; i++) {
if (charCount[i] != 0) {
return false;
}
}
return true;
}
/**
* Main method to test the anagram checking function.
*
* @return Exit status of the program.
*/
int main() {
// Example strings
char str1[] = "listen";
char str2[] = "silent";
// Check if the strings are anagrams
if (areAnagrams(str1, str2)) {
printf("%s and %s are anagrams.\n", str1, str2);
} else {
printf("%s and %s are not anagrams.\n", str1, str2);
}
return 0;
}
Explanation
The program consists of two main parts:
areAnagrams
function: This function takes two strings as input and checks if they are anagrams. It does so by using an array to count the frequency of each character in the strings. If the counts match for all characters, the strings are anagrams.main
function: This is the entry point of the program. It defines two example strings, calls theareAnagrams
function, and prints whether the strings are anagrams or not.
Key Points:
- The function first checks if the lengths of the strings are different. If they are, the strings cannot be anagrams.
- An array
charCount
is used to store the frequency of each character. The array is initialized to zero. - The function iterates through the first string, incrementing the count for each character. It then iterates through the second string, decrementing the count for each character.
- Finally, the function checks if all counts in the
charCount
array are zero. If they are, the strings are anagrams; otherwise, they are not.