
168 views
Anagram in C
An anagram is a word or phrase formed by rearranging the letters of another word or phrase while using all the original letters exactly once. To determine if two strings are anagrams in C, you can follow these steps:
- Create a function to check if two strings are anagrams.
- Count the occurrences of each character in both strings.
- Compare the character counts to check if they match.
Here’s a C program to check if two strings are anagrams:
C
#include <stdio.h>
#include <string.h>
// Function to check if two strings are anagrams
int areAnagrams(const char* str1, const char* str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
// If the lengths are different, the strings cannot be anagrams
if (len1 != len2) {
return 0;
}
// Arrays to store character counts for each string
int count1[256] = {0}; // Assuming ASCII characters
int count2[256] = {0};
// Count characters in the first string
for (int i = 0; i < len1; i++) {
count1[(int)str1[i]]++;
}
// Count characters in the second string
for (int i = 0; i < len2; i++) {
count2[(int)str2[i]]++;
}
// Compare character counts
for (int i = 0; i < 256; i++) {
if (count1[i] != count2[i]) {
return 0; // Character counts do not match
}
}
return 1; // The strings are anagrams
}
int main() {
const char* word1 = "listen";
const char* word2 = "silent";
if (areAnagrams(word1, word2)) {
printf("'%s' and '%s' are anagrams.\n", word1, word2);
} else {
printf("'%s' and '%s' are not anagrams.\n", word1, word2);
}
return 0;
}
In this program:
- The
areAnagrams
function takes two strings (str1
andstr2
) as input and returns 1 if they are anagrams, and 0 if they are not. - It first checks if the lengths of the two strings are equal because anagrams must have the same number of characters.
- It uses arrays
count1
andcount2
to store the counts of each character in both strings. - It counts the characters in both strings and then compares the character counts. If the counts for all characters match, the strings are considered anagrams.
The program checks if the words “listen” and “silent” are anagrams and prints the result. You can replace these words with any other words you want to check for anagrams.