Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Check whether two strings are anagram of each other in C with character count method?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 755
    Comment on it
    # include <stdio.h>
    # define NO_OF_CHARS 256
     
    bool areAnagram(char *str1, char *str2) //function checks whether two strings are anagrams.
    {
        // Create 2 count arrays and initialize all values as 0
        int count1[NO_OF_CHARS] = {0};
        int count2[NO_OF_CHARS] = {0};
        int i;
     
        // For each character in input strings, increment count in
        // the corresponding count array
        for (i = 0; str1[i] && str2[i];  i++)
        {
            count1[str1[i]]++;
            count2[str2[i]]++;
        }
     
        if (str1[i] || str2[i]) //checking whether length of strings are same
          return false;
     
        
        for (i = 0; i < NO_OF_CHARS; i++)  // Compare count arrays
            if (count1[i] != count2[i])
                return false;
     
        return true;
    }
    
    int main()
    {
        char str1[] = "demo";
        char str2[] = "emdo";
        if ( areAnagram(str1, str2) )
          printf("The two strings are anagram of each other");
        else
          printf("The two strings are not anagram of each other");
     
        return 0;
    }

    Output:

    The two strings are anagram of each other

    Explanation:

    An anagram of a string can be defined as another string that contains same characters, only ordering of characters can be different. In the above program following procedure is followed:-

    1) For both strings count arrays of size 256 are created. Then all values in count arrays are initialized to 0.
    2) In count array character count is incremented as every character of both string are iterated.
    3) Compare count arrays as well as lengths of both strings. If both count arrays are same, then return true else false.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: