Write a function which, given 2 strings, determines whether one is an anagram of the other i.e. one string is a permutation of characters in the other e.g. team and mate.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <string.h>

#define SIZE 100

int check_anagram(char [], char []);

int main(void)
{
    char a[SIZE], b[SIZE];
    int flag;

    printf("Enter first string:");
    fgets(a, SIZE, stdin);
    a[strcspn(a, "\n")] = 0;

    printf("Enter second string:");
    fgets(b, SIZE, stdin);
    b[strcspn(b, "\n")] = 0;

    flag = check_anagram(a, b);

    if (flag == 1)
        printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
    else
        printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);

    return 0;
}

int check_anagram(char a[], char b[])
{
    int first[26] = {0}, second[26] = {0}, c = 0;

    while (a[c] != '\0')
    {
        first[a[c]-'a']++;
        c++;
    }

    c = 0;

    while (b[c] != '\0')
    {
        second[b[c]-'a']++;
        c++;
    }

    for (c = 0; c < 26; c++)
    {
        if (first[c] != second[c])
            return 0;
    }

    return 1;
}

When you compile and execute the above program it produces the following result on Linux:

Enter first string:team
Enter second string:mate
"team" and "mate" are anagrams.

Brief Explanation

  • Two words are said to be anagrams of each other if the letters from one word can be rearranged to form the other word. From the above definition it is clear that two strings are anagrams if all characters in both strings occur same number of times. For example "abc" and "cab" are anagram strings, here every character 'a', 'b' and 'c' occur only one time in both strings.
  • The program tries to find how many times characters appear in the strings and then comparing their corresponding counts. It does so by using the function check_anagram which takes the two strings as parameters and returns 0 if the strings are not anagrams and 1 if they are anagrams of each other.

Add comment


Security code
Refresh