C# Anagram Checker

24 Apr, 2013
Updated
22 Dec, 2012
Created

A while ago, during an interview I was asked to write a function that takes two strings and returns true when the strings are anagrams of each other and otherwise returns false.

Now there are numerous ways to check for anagrams. Perhaps the most commonly used and simplest approach is to sort the individual characters of each string in some collection and compare them. If both sorted collections are equal, we can say that the second string is an anagram of the first string (often referred to as the subject).

An Example

Let us consider an example. The strings “Debit Card” and “Bad Credit” are anagrams of each other. Based on our approach mentioned above, we can arrange the characters in “Debit Card” alphabetically into a character array. The resulting array will be [‘a’, ‘b’, ‘c’, ‘d’, ‘d’, ‘e’, ‘i’, ‘r’, ‘t’]. Similarly, lets take the characters of the string “Bad Credit” into a character array. The array will be [‘b’, ‘a’, ‘d’, ‘c’, ‘r’, ‘e’, ‘d’, ‘i’, ‘t’]. If we arrange this second array in alphabetical order, we get [‘a’, ‘b’, ‘c’, ‘d’, ‘d’, ‘e’, ‘i’, ‘r’, ‘t’]. Comparing the two arrays we find that they are identical and hence we can conclude that “Bad Credit” is an anagram of “Debit Card”.

The Code in C#

Here’s the code that does checks if two strings are anagrams and returns true if they are.

Explanation

You might be wondering why I have a third parameter in the function definition. I have placed this deliberately to help me when I am writing unit tests as well as to know exactly why and where the check fails in case the strings are not anagrams. The following code displays sample unit tests for the above function.