How to check if two Strings are anagrams of each other using C#?

CsharpProgrammingServer Side Programming

Under anagram, another string would have the same characters present in the first string, but the order of characters can be different.

Here, we are checking the following two strings −

string str1 = "silent";
string str2 = "listen";

Convert both the strings into character array −

char[] ch1 = str1.ToLower().ToCharArray();
char[] ch2 = str2.ToLower().ToCharArray();

Now, sort them −

Array.Sort(ch1);
Array.Sort(ch2);

After sorting, convert them to strings −

string val1 = new string(ch1);
string val2 = new string(ch2);

Compare both the strings for equality. If both are equal, that would mean they are anagrams.

The following is the code −

Example

 Live Demo

using System;

public class Demo {
   public static void Main () {
      string str1 = "silent";
      string str2 = "listen";
      char[] ch1 = str1.ToLower().ToCharArray();
      char[] ch2 = str2.ToLower().ToCharArray();
      Array.Sort(ch1);
      Array.Sort(ch2);
      string val1 = new string(ch1);
      string val2 = new string(ch2);

      if (val1 == val2) {
         Console.WriteLine("Both the strings are Anagrams");
      } else {
         Console.WriteLine("Both the strings are not Anagrams");
      }
   }
}

Output

Both the strings are Anagrams
raja
Published on 31-Aug-2018 12:37:04
Advertisements