How To Check If Two Strings Are Anagrams Of Each Other

Hello all, In this blog we will see how to check if given two strings are anagram of each other or not.

So to understand this program better, first we need to understand what is an anagram. As per the Google defination, "An anagram of a string is another string that contains the same characters, only the order of characters can be different."

Step 1

First take two string inputs from the user and assign it to proper string variables.

Step 2

In this step convert string to character array, also make the string in lower case to get proper output.

Step 3

Sort both the character array that you just converted in the above step.

Step 4

Now convert character array back to string, make sure to use a different variable name to store the result to avoid confusion.

Step 5

In the 4th step you got the result in two string variables, compare them, if both the strings are same, it means provided strings are anagram of each other otherwise It won't be anagram if both the output not same.

Check the below code. to watch the video click Here

using System;
namespace ConsoleApp {
    class AnagramString {
        static void Main(string[] args) {
            //Step 1
            string s1, s2;
            Console.Write("Enter first string: ");
            s1 = Console.ReadLine();
            Console.Write("Enter second string: ");
            s2 = Console.ReadLine();
            //step 2
            char[] a1 = s1.ToLower().ToCharArray();
            char[] a2 = s2.ToLower().ToCharArray();
            //step 3
            Array.Sort(a1);
            Array.Sort(a2);
            //step 4
            string res1 = new string(a1);
            string res2 = new string(a2);
            //step 5
            if (res1 == res2) Console.WriteLine("Strings are anagram.");
            else Console.WriteLine("Strings are not anagram.");
            Console.ReadLine();
        }
    }
}