Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check if two Strings are anagrams of each other using C#?
An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For example, "silent" and "listen" are anagrams because they contain the same letters in different arrangements.
In C#, there are several approaches to check if two strings are anagrams. The most common method is to sort the characters of both strings and compare them for equality.
Using Array.Sort() Method
The simplest approach is to convert both strings to character arrays, sort them, and then compare the sorted arrays −
Example
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 strings are anagrams");
} else {
Console.WriteLine("Both strings are not anagrams");
}
}
}
The output of the above code is −
Both strings are anagrams
Using Character Frequency Count
An alternative approach counts the frequency of each character in both strings. If the frequencies match, the strings are anagrams −
Example
using System;
using System.Collections.Generic;
public class AnagramChecker {
public static bool AreAnagrams(string str1, string str2) {
if (str1.Length != str2.Length) {
return false;
}
Dictionary<char, int> charCount = new Dictionary<char, int>();
// Count characters in first string
foreach (char c in str1.ToLower()) {
if (charCount.ContainsKey(c)) {
charCount[c]++;
} else {
charCount[c] = 1;
}
}
// Subtract counts for second string
foreach (char c in str2.ToLower()) {
if (!charCount.ContainsKey(c)) {
return false;
}
charCount[c]--;
if (charCount[c] == 0) {
charCount.Remove(c);
}
}
return charCount.Count == 0;
}
public static void Main() {
string str1 = "race";
string str2 = "care";
Console.WriteLine($"'{str1}' and '{str2}' are anagrams: {AreAnagrams(str1, str2)}");
str1 = "hello";
str2 = "world";
Console.WriteLine($"'{str1}' and '{str2}' are anagrams: {AreAnagrams(str1, str2)}");
}
}
The output of the above code is −
'race' and 'care' are anagrams: True 'hello' and 'world' are anagrams: False
Using LINQ
A concise approach using LINQ to order the characters and compare −
Example
using System;
using System.Linq;
public class LinqAnagram {
public static bool CheckAnagram(string str1, string str2) {
return str1.ToLower().OrderBy(c => c).SequenceEqual(
str2.ToLower().OrderBy(c => c));
}
public static void Main() {
string[] pairs = { "listen", "silent", "elbow", "below", "study", "dusty" };
for (int i = 0; i < pairs.Length; i += 2) {
bool result = CheckAnagram(pairs[i], pairs[i + 1]);
Console.WriteLine($"'{pairs[i]}' and '{pairs[i + 1]}': {result}");
}
}
}
The output of the above code is −
'listen' and 'silent': True 'elbow' and 'below': True 'study' and 'dusty': True
Comparison
| Method | Time Complexity | Space Complexity | Advantages |
|---|---|---|---|
| Array.Sort() | O(n log n) | O(n) | Simple and straightforward |
| Character Count | O(n) | O(1) | Most efficient for large strings |
| LINQ | O(n log n) | O(n) | Concise and readable |
Conclusion
Checking for anagrams in C# can be accomplished through sorting characters, counting character frequencies, or using LINQ. The character frequency method is most efficient with O(n) time complexity, while sorting approaches offer simplicity and readability for smaller datasets.
