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.
- Convert both strings to character arrays.
- Sort the character arrays in ascending/descending order, but use the same ordering on both of the character sets.
- Create two strings out of the two sorted character set arrays.
- Compare the strings.
- If they are not equal, they are not Anagrams.
Code
- using System;
- namespace Anagram
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- Console.Write("Enter first word:");
- string word1 = Console.ReadLine();
- Console.Write("Enter second word:");
- string word2 = Console.ReadLine();
-
-
-
-
-
- char[] char1 = word1.ToLower().ToCharArray();
- char[] char2 = word2.ToLower().ToCharArray();
-
-
- Array.Sort(char1);
- Array.Sort(char2);
-
-
- string NewWord1 = new string(char1);
- string NewWord2 = new string(char2);
-
-
-
-
- if (NewWord1 == NewWord2)
- {
- Console.WriteLine("Yes! Words \"{0}\" and \"{1}\" are Anagrams", word1, word2);
- }
- else
- {
- Console.WriteLine("No! Words \"{0}\" and \"{1}\" are not Anagrams", word1, word2);
- }
-
-
- Console.ReadLine();
- }
- }
- }
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.