Monday, 25 May 2015

Anagram strings

Anagram Strings:-- Two strings are said to be anagram if they consist of same set of characters with same frequency.
example :-- lab 
                   bla
These two strings are anagram

                   lab
                   bll
These are not anagrams


C code to find whether the strings are anagram or not

#include<stdio.h>
int anagram(char [],char []);
int main()
{
    char a[100];
    char b[100];
    int f=0;
    printf("Enter the first string\n");
    gets(a);
    printf("Enter the second string\n");
    gets(b);
    f=anagram(a,b);
    if(f==1)
    {
        printf("The entered strings are anagram\n");
    }
    else
    {
        printf("The entered strings are not anagram\n");
    }
    return 0;
}

int anagram(char a[],char b[])
{
    int a1[26]={0};
    int a2[26]={0};
    int i=0;
    while(a[i]!='\0')
    {
        a1[a[i]-'a']++;
        i++;
    }
    i=0;
    while(b[i]!='\0')
    {
        a2[a[i]-'a']++;
        i++;
    }
    int temp=0;
    for(temp=0;temp<26;temp++)
    {
        if(a1[temp]!=a2[temp])
        {
            return 0;
        }
    else
    {
        return 1;
    }
    }
}

No comments:

Post a Comment