How to Determine if Two Words Are Anagrams of Each Other in C#

Anagrams

Two words are said to be Anagrams of each other if they share the same set of letters to form the respective words. Remember, it’s just rearranging the existing letter set. For example, Silent and Listen.

The following example is not an Anagram, since we use one “I” in DIANA and two “a”s whereas INDIA has two “I”s and one “a”.

For example, INDIA & DIANA.

Logic

The following is the logic.

  1. Convert both strings to character arrays.
  2. Sort the character arrays in ascending/descending order, but use the same ordering on both of the character sets.
  3. Create two strings out of the two sorted character set arrays.
  4. Compare the strings.
  5. If they are not equal, they are not Anagrams.

Code

  1. using System;  
  2. namespace Anagram  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.            //Receive Words from User  
  9.             Console.Write("Enter first word:");  
  10.             string word1 = Console.ReadLine();  
  11.             Console.Write("Enter second word:");  
  12.             string word2 = Console.ReadLine();  
  13.    
  14.             //Add optional validation of input words if needed.  
  15.             //.....  
  16.    
  17.             //step 1  
  18.             char[] char1 = word1.ToLower().ToCharArray();  
  19.             char[] char2 = word2.ToLower().ToCharArray();  
  20.    
  21.             //Step 2  
  22.             Array.Sort(char1);  
  23.             Array.Sort(char2);  
  24.    
  25.             //Step 3  
  26.             string NewWord1 = new string(char1);  
  27.             string NewWord2 = new string(char2);  
  28.    
  29.             //Step 4  
  30.             //ToLower allows to compare the words in same case, in this case, lower case.  
  31.             //ToUpper will also do exact same thing in this context  
  32.             if (NewWord1 == NewWord2)  
  33.             {  
  34.                 Console.WriteLine("Yes! Words \"{0}\" and \"{1}\" are Anagrams", word1, word2);  
  35.             }  
  36.             else  
  37.             {  
  38.                 Console.WriteLine("No! Words \"{0}\" and \"{1}\" are not Anagrams", word1, word2);  
  39.             }  
  40.    
  41.             //Hold Console screen alive to view the results.  
  42.             Console.ReadLine();  
  43.         }  
  44.     }  
  45. }  
Word of Caution

To enable case insensitivity, you must use the ToLower() method on the input words prior to the sort. Sort puts uppercase letters ahead of lowercase. Let us say you do not use ToLower() prior to sort, the sorting of the word “Game” will be “Gaem”, instead “aeGm”.

Happy Coding.


Recommended Free Ebook
Similar Articles