Anagram Check Program in C
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, ‘listen’ is an anagram of ‘silent’.
Program Structure
The C program below checks if two given strings are anagrams of each other. The program performs the following steps:
- Check if the lengths of both strings are equal. If not, they cannot be anagrams.
- Sort both strings.
- Compare the sorted strings. If they are identical, then the original strings are anagrams; otherwise, they are not.
Code
#include
#include
#include
// Function to sort a string in alphabetical order
void sortString(char *str) {
int length = strlen(str);
char temp;
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++) { if (str[i] > str[j]) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
// Function to check if two strings are anagrams
int areAnagrams(char *str1, char *str2) {
// Remove spaces and convert to lowercase
char cleanedStr1[100], cleanedStr2[100];
int index1 = 0, index2 = 0;
for (int i = 0; str1[i]; i++) {
if (!isspace(str1[i])) {
cleanedStr1[index1++] = tolower(str1[i]);
}
}
cleanedStr1[index1] = '\0';
for (int i = 0; str2[i]; i++) {
if (!isspace(str2[i])) {
cleanedStr2[index2++] = tolower(str2[i]);
}
}
cleanedStr2[index2] = '\0';
// Check if lengths are different
if (strlen(cleanedStr1) != strlen(cleanedStr2)) {
return 0;
}
// Sort both strings
sortString(cleanedStr1);
sortString(cleanedStr2);
// Compare sorted strings
return strcmp(cleanedStr1, cleanedStr2) == 0;
}
int main() {
char str1[100], str2[100];
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = '\0'; // Remove trailing newline
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = '\0'; // Remove trailing newline
if (areAnagrams(str1, str2)) {
printf("The strings are anagrams.\n");
} else {
printf("The strings are not anagrams.\n");
}
return 0;
}
Explanation
The sortString function sorts the characters of the given string in alphabetical order. The areAnagrams function checks if two strings are anagrams by first removing spaces and converting characters to lowercase. It then compares the lengths of the cleaned strings, sorts them, and compares the sorted results. The main function reads two strings from the user, processes them using areAnagrams, and prints whether they are anagrams or not.
