0
0
CsharpProgramBeginner · 2 min read

C# Program to Check Anagram with Example and Explanation

To check if two strings are anagrams in C#, convert both strings to lowercase, remove spaces, sort their characters using ToCharArray() and Array.Sort(), then compare the sorted arrays with SequenceEqual().
📋

Examples

Input"listen", "silent"
OutputTrue
Input"hello", "world"
OutputFalse
Input"Dormitory", "Dirty room"
OutputTrue
🧠

How to Think About It

To check if two words are anagrams, first treat them the same by ignoring case and spaces. Then, sort the letters of each word alphabetically. If the sorted letters match exactly, the words are anagrams because they have the same letters in the same amounts.
📐

Algorithm

1
Get two input strings.
2
Convert both strings to lowercase and remove spaces.
3
Convert each string to a character array.
4
Sort both character arrays alphabetically.
5
Compare the sorted arrays; if they are equal, return true, else false.
💻

Code

csharp
using System;
using System.Linq;

class Program {
    static bool AreAnagrams(string s1, string s2) {
        var arr1 = s1.ToLower().Replace(" ", "").ToCharArray();
        var arr2 = s2.ToLower().Replace(" ", "").ToCharArray();
        Array.Sort(arr1);
        Array.Sort(arr2);
        return arr1.SequenceEqual(arr2);
    }

    static void Main() {
        Console.WriteLine(AreAnagrams("listen", "silent"));
        Console.WriteLine(AreAnagrams("hello", "world"));
        Console.WriteLine(AreAnagrams("Dormitory", "Dirty room"));
    }
}
Output
True False True
🔍

Dry Run

Let's trace the example "Dormitory" and "Dirty room" through the code.

1

Normalize strings

"Dormitory" -> "dormitory", "Dirty room" -> "dirtyroom" (lowercase and no spaces)

2

Convert to char arrays

arr1 = ['d','o','r','m','i','t','o','r','y'], arr2 = ['d','i','r','t','y','r','o','o','m']

3

Sort arrays

arr1 sorted = ['d','i','m','o','o','r','r','t','y'], arr2 sorted = ['d','i','m','o','o','r','r','t','y']

4

Compare arrays

Both sorted arrays are equal, so return True

Steparr1arr2
Initialdormitorydirtyroom
After sortd i m o o r r t yd i m o o r r t y
💡

Why This Works

Step 1: Normalize input

We convert both strings to lowercase and remove spaces to treat letters equally regardless of case or gaps.

Step 2: Sort characters

Sorting the characters puts letters in order, so if two strings have the same letters, their sorted forms will match.

Step 3: Compare sorted arrays

If the sorted character arrays are exactly the same, the strings are anagrams; otherwise, they are not.

🔄

Alternative Approaches

Using character frequency count
csharp
using System;
using System.Collections.Generic;

class Program {
    static bool AreAnagrams(string s1, string s2) {
        var dict = new Dictionary<char, int>();
        foreach (var c in s1.ToLower().Replace(" ", "")) {
            dict[c] = dict.GetValueOrDefault(c, 0) + 1;
        }
        foreach (var c in s2.ToLower().Replace(" ", "")) {
            if (!dict.ContainsKey(c)) return false;
            dict[c]--;
            if (dict[c] < 0) return false;
        }
        return true;
    }

    static void Main() {
        Console.WriteLine(AreAnagrams("listen", "silent"));
        Console.WriteLine(AreAnagrams("hello", "world"));
        Console.WriteLine(AreAnagrams("Dormitory", "Dirty room"));
    }
}
This method counts letters instead of sorting; it can be faster for very long strings but uses extra memory.
Using LINQ GroupBy and All
csharp
using System;
using System.Linq;

class Program {
    static bool AreAnagrams(string s1, string s2) {
        var a = s1.ToLower().Replace(" ", "").GroupBy(c => c).OrderBy(g => g.Key);
        var b = s2.ToLower().Replace(" ", "").GroupBy(c => c).OrderBy(g => g.Key);
        return a.SequenceEqual(b, new CharGroupComparer());
    }

    class CharGroupComparer : IEqualityComparer<IGrouping<char, char>> {
        public bool Equals(IGrouping<char, char> x, IGrouping<char, char> y) {
            return x.Key == y.Key && x.Count() == y.Count();
        }
        public int GetHashCode(IGrouping<char, char> obj) => obj.Key.GetHashCode();
    }

    static void Main() {
        Console.WriteLine(AreAnagrams("listen", "silent"));
        Console.WriteLine(AreAnagrams("hello", "world"));
        Console.WriteLine(AreAnagrams("Dormitory", "Dirty room"));
    }
}
This LINQ-based method is elegant and readable but more complex and slightly slower.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting each string takes O(n log n) time where n is the string length, which dominates the runtime.

Space Complexity

Extra space is used for character arrays and sorting, so space complexity is O(n).

Which Approach is Fastest?

Counting characters with a dictionary can be faster (O(n)) than sorting but uses more memory; sorting is simpler and good for short strings.

ApproachTimeSpaceBest For
Sorting and comparingO(n log n)O(n)Simple and short strings
Character frequency countO(n)O(n)Long strings, performance critical
LINQ GroupBy methodO(n log n)O(n)Readable code, moderate performance
💡
Always normalize strings by lowercasing and removing spaces before checking for anagrams.
⚠️
Forgetting to ignore case and spaces causes correct anagrams to be marked false.