C# How To Check if Two Strings Are Anagrams
Check Anagram
Two words are anagrams if they have the same letters in a different order, like "listen" and "silent". Sort the letters of both words, and compare them:
Example
string word1 = "listen";
string word2 = "silent";
char[] chars1 = word1.ToCharArray();
char[] chars2 = word2.ToCharArray();
Array.Sort(chars1);
Array.Sort(chars2);
if (new string(chars1) == new string(chars2))
{
Console.WriteLine("The words are anagrams");
}
else
{
Console.WriteLine("The words are not anagrams");
}
Explanation:Array.Sort() puts the letters of each word in alphabetical order. Both words become "eilnst".
If the sorted words are equal, the two words have the same letters.