Exploring Anagram Strings in C#

Introduction

Anagrams are fascinating linguistic puzzles where rearranging the letters of a word or phrase results in a new word or phrase with the same letters but in a different order. In this article, we'll delve into how we can leverage the power of C# to solve anagrams, exploring various techniques and algorithms along the way.

Understanding Anagrams

Before diving into the implementation, let's ensure a clear understanding of what constitutes an anagram. Two strings are considered anagrams if they contain the same characters with the same frequency but in a different order. For example, "listen" and "silent" are anagrams because both contain the same letters ('l', 'i', 's', 't', 'e', 'n'). 

We will explore three ways to solve this problem.

Using Sorting

One of the simplest methods to check if two strings are anagrams is by sorting their characters and comparing the sorted strings. Let's implement this approach in C#.

using System;

class AnagramChecker
{
    static bool AreAnagrams(string str1, string str2)
    {
        // Check if the lengths are different
        if (str1.Length != str2.Length)
            return false;

        // Convert strings to character arrays and sort them
        char[] charArray1 = str1.ToCharArray();
        char[] charArray2 = str2.ToCharArray();
        Array.Sort(charArray1);
        Array.Sort(charArray2);

        // Compare sorted strings
        for (int i = 0; i < str1.Length; i++)
        {
            if (charArray1[i] != charArray2[i])
                return false;
        }
        return true;
    }

    static void Main(string[] args)
    {
        string str1 = "listen";
        string str2 = "silent";

        if (AreAnagrams(str1, str2))
            Console.WriteLine("The strings are anagrams.");
        else
            Console.WriteLine("The strings are not anagrams.");
    }
}

Using Frequency Count

Another approach is to count the frequency of characters in both strings and ensure that the frequencies match for each character. Let's implement this approach.

using System;
using System.Collections.Generic;

class AnagramChecker
{
    static bool AreAnagrams(string str1, string str2)
    {
        // Check if the lengths are different
        if (str1.Length != str2.Length)
            return false;

        // Create dictionaries to store character frequencies
        Dictionary<char, int> freq1 = new Dictionary<char, int>();
        Dictionary<char, int> freq2 = new Dictionary<char, int>();

        // Count frequencies for string 1
        foreach (char c in str1)
        {
            if (freq1.ContainsKey(c))
                freq1[c]++;
            else
                freq1[c] = 1;
        }

        // Count frequencies for string 2
        foreach (char c in str2)
        {
            if (freq2.ContainsKey(c))
                freq2[c]++;
            else
                freq2[c] = 1;
        }

        // Compare frequencies
        foreach (var pair in freq1)
        {
            if (!freq2.ContainsKey(pair.Key) || freq2[pair.Key] != pair.Value)
                return false;
        }
        return true;
    }

    static void Main(string[] args)
    {
        string str1 = "listen";
        string str2 = "silent";

        if (AreAnagrams(str1, str2))
            Console.WriteLine("The strings are anagrams.");
        else
            Console.WriteLine("The strings are not anagrams.");
    }
}

Using Bubble Sort Algorithm

Using bubble sort for anagram comparison is not the most efficient approach due to its time complexity, it can still serve as a good exercise to understand the algorithm. Here's an implementation using bubble sort.

using System;

class AnagramChecker
{
    // Bubble sort implementation
    static void BubbleSort(char[] arr)
    {
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (arr[j] > arr[j + 1])
                {
                    // Swap elements
                    char temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    // Function to check if two strings are anagrams using bubble sort
    static bool AreAnagrams(string str1, string str2)
    {
        // Check if the lengths are different
        if (str1.Length != str2.Length)
            return false;

        // Convert strings to character arrays
        char[] charArray1 = str1.ToCharArray();
        char[] charArray2 = str2.ToCharArray();

        // Sort character arrays
        BubbleSort(charArray1);
        BubbleSort(charArray2);

        // Compare sorted strings
        for (int i = 0; i < str1.Length; i++)
        {
            if (charArray1[i] != charArray2[i])
                return false;
        }

        return true;
    }

    static void Main(string[] args)
    {
        string str1 = "listen";
        string str2 = "silent";

        if (AreAnagrams(str1, str2))
            Console.WriteLine("The strings are anagrams.");
        else
            Console.WriteLine("The strings are not anagrams.");
    }
}

In this implementation, we define the BubbleSort method to sort the characters of an array using the bubble sort algorithm. Then, we use this method within the AreAnagrams function to sort the characters of both input strings before comparing them. If the sorted strings are equal, the input strings are considered anagrams. Otherwise, they are not.

Conclusion

In this article, we explored three approaches to determine whether two strings are anagrams in C#. All methods have their advantages and can be chosen based on the specific requirements of the application. Anagrams present an interesting problem that showcases the versatility of programming languages like C#.

Thank You, and Stay Tuned for More

More Articles from my Account


Similar Articles