Check If Two Strings Are Anagrams Of Each Other

Hello all, In this article, I will explain how to check whether the two strings are an Anagram of each other or not.

What is an Anagram?

As per the Google definition, “An anagram of a string is another string that contains the same characters, only the order of characters can be different.” In other words, if the letters of one word or phrase can be rearranged to form another word or phrase, then the two words or phrases are considered to be anagrams of each other.

How to Check?

To check if two strings are anagrams of each other in C#, you can compare the sorted versions of the strings. Anagrams are words or phrases formed by rearranging the letters of a different word or phrase, so if two strings are anagrams of each other, they will contain the same letters in the same quantity, but in a different order.

using System;

namespace AnagramString
{
    class Program
    {
        static void Main(string[] args)
        {
            string word1 = "listen";
            string word2 = "silent";

            if (CheckAnagrams(word1, word2))
            {
                Console.WriteLine("'{0}' and '{1}' are anagrams.", word1, word2);
            }
            else
            {
                Console.WriteLine("'{0}' and '{1}' are not anagrams.", word1, word2);
            }
            Console.ReadLine();
        }
        static bool CheckAnagrams(string str1, string str2)
        {
            char[] char1 = str1.ToCharArray();
            char[] char2 = str2.ToCharArray();

            Array.Sort(char1);
            Array.Sort(char2);

            return new string(char1) == new string(char2);
        }
    }
}

In the above example, the CheckAnagrams function takes two string arguments and returns the boolean indicating whether the strings are anagrams of each other. In the function, we first convert the strings to character arrays using the ToCharArray() method. We then sort the character arrays using the Array.Sort() method. Then we compare the sorted character arrays by creating new strings from them using the new string(char[]) constructor and comparing the resulting strings using the == operator. If the sorted strings are equal, the original strings are anagrams of each other and we return true. Otherwise, we return false.

Output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories