Wednesday, 24 September 2014

CHECKING IF THE TWO GIVEN STRINGS ARE ANAGRAMS OR NOT

String1 is said to be the ANAGRAM of String2 if the characters of String1 can be jumbled up to form String2. To check for ANAGRAMS, the length of the two strings has to be same.

For example, BUTTERFLY  and TTFYLUBRE are ANAGRAMS.
                      MOUSE and UESOME are not ANAGRAMS as the lengths vary.
                      LABEL and BBALE are not ANAGRAMS as the characters of the two strings
                      are not same.

Source Code:-
********************************************************
#include<stdio.h>
#include<string.h>

int isAnagram(char str1[],char str2[]);

int main()
{
    char str1[100],str2[100];
    int r;
    printf("\nEnter first string:");
    gets(str1);
    printf("\nEnter second string:");
    gets(str2);
    if(strlen(str1)==strlen(str2))/*if length of the 2 strings are not equal,
                                    they are not anagrams.*/
    {
        r=isAnagram(str1,str2);
        if(r==1)
            printf("TRUE");
        else
            printf("FALSE");
    }
    else
        printf("FALSE");
    return 0;
}


int isAnagram(char str1[],char str2[]) //function to check if 2 strings are anagrams.
{
    int abc1[128],abc2[128],i;

    /*the length of the two arrays is chosen as 128 as basic ASCII code is from 0 to 127.
    so checking for all characters becomes quite easy and fast.*/

    for(i=0;i<128;i++)
    {
        abc1[i]=abc2[i]=0;
    }

    /*For a given character in a string,incrementation is done in
      the array at the character's corresponding ascii index*/

    for(i=0;str1[i]!='\0';i++)
        abc1[(int)str1[i]]++;

    for(i=0;str2[i]!='\0';i++)
        abc2[(int)str2[i]]++;

    for(i=0;i<128;i++)//if the 2 arrays are equal,the strings are Anagrams.
    {
        if(abc1[i]!=abc2[i])
            return 0;
    }
    return 1;
}


********************************************************

No comments:

Post a Comment