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
    • 797
    Comment on it
    1. # include <stdio.h>
    2. # define NO_OF_CHARS 256
    3. bool areAnagram(char *str1, char *str2) //function checks whether two strings are anagrams.
    4. {
    5. // Create 2 count arrays and initialize all values as 0
    6. int count1[NO_OF_CHARS] = {0};
    7. int count2[NO_OF_CHARS] = {0};
    8. int i;
    9. // For each character in input strings, increment count in
    10. // the corresponding count array
    11. for (i = 0; str1[i] && str2[i]; i++)
    12. {
    13. count1[str1[i]]++;
    14. count2[str2[i]]++;
    15. }
    16. if (str1[i] || str2[i]) //checking whether length of strings are same
    17. return false;
    18. for (i = 0; i < NO_OF_CHARS; i++) // Compare count arrays
    19. if (count1[i] != count2[i])
    20. return false;
    21. return true;
    22. }
    23.  
    24. int main()
    25. {
    26. char str1[] = "demo";
    27. char str2[] = "emdo";
    28. if ( areAnagram(str1, str2) )
    29. printf("The two strings are anagram of each other");
    30. else
    31. printf("The two strings are not anagram of each other");
    32. return 0;
    33. }

    Output:

    1. 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
Reset Password
Fill out the form below and reset your password: