Words are called anagrams of if they all share the same set of letters to form the respective words.
Example:
Dealer –>Leader,
POT–> Top –>Opt ,
Dear –> Read
In this post, I am giving the sample code to check whether two words are anagrams
Anagrams Check in C#
/// <summary>
/// Determine if the two strings are anagrams
/// </summary>
public static string CheckAnagrams(string wrd1,string wrd2)
{
//Split the words into char array
char[] wrd1Array = wrd1.ToUpper().ToCharArray();
char[] wrd2Array = wrd2.ToUpper().ToCharArray();
//Sort the char array to arrange chars alphabetically
Array.Sort(wrd1Array);
Array.Sort(wrd2Array);
//make char arrays as strings to compare
string NewWord1 = new string(wrd1Array);
string NewWord2 = new string(wrd2Array);
//Compare the two strings
if (NewWord1 == NewWord2)
return wrd1 + " and "+ wrd2 +" are Anagrams";
else
return wrd1 + " and " + wrd2 + " are not Anagrams";
}
Anagrams Check in VB.NET
''' <summary>
''' Determine if the two strings are anagrams
''' </summary>
Public Shared Function CheckAnagrams(wrd1 As String, wrd2 As String) As String
'Split the words into char array
Dim wrd1Array As Char() = wrd1.ToUpper().ToCharArray()
Dim wrd2Array As Char() = wrd2.ToUpper().ToCharArray()
'Sort the char array to arrange chars alphabetically
Array.Sort(wrd1Array)
Array.Sort(wrd2Array)
'make char arrays as strings to compare
Dim NewWord1 As New String(wrd1Array)
Dim NewWord2 As New String(wrd2Array)
'Compare the two strings
If NewWord1 = NewWord2 Then
Return (Convert.ToString(wrd1 & Convert.ToString(" and ")) & wrd2) + " are Anagrams"
Else
Return (Convert.ToString(wrd1 & Convert.ToString(" and ")) & wrd2) + " are not Anagrams"
End If
End Function
Leave a Reply