C# Code Examples

Check Whether Two Strings are Anagrams in C#

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

Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

2 years ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

2 years ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

2 years ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

2 years ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

2 years ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

2 years ago