Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of an anagram function in C#

Tags:

c#

Possible Duplicate:
What is an easy way to tell if a list of words are anagrams of each other?

What is the best way (performance wide) to write a function in C# that takes two strings and returns true when the strings are anagrams of each other and otherwise returns false. Example of anagrams are:

abet beat beta bate
abides biased

anagrams link

In implementing this, is it possible that there is space in each string?

Any idea would be very much appreciated!

like image 416
Pingpong Avatar asked Aug 16 '11 02:08

Pingpong


People also ask

What is anagram program in C?

In other words, anagrams are a technique of C programming that checks whether a given string contains the same number of characters, except that the sequence of characters can be changed in both strings.

What is anagram algorithm?

The anagram algorithm is a simple algorithm. Create a function where you compare two strings and check if they are anagrams of each other. The strings can contain any type of characters like “Hi, there!” and “There…


2 Answers

A simple (naïve?) way, using LINQ:

"abides".OrderBy(c=>c).SequenceEqual("biased".OrderBy(c=>c))
like image 72
porges Avatar answered Oct 17 '22 00:10

porges


An easy solution would be to sort the characters alphabetically and compare them to one another.

public static class AnagramExtensions
{
    public static bool IsAnagramOf(this string word1, string word2)
    {
        return word1.OrderBy(x => x).SequenceEqual(word2.OrderBy(x => x));
    }
}

Then, to use it:

    static void Main()
    {
        string word1 = "cat";
        string word2 = "tac";

        Console.WriteLine(word1.IsAnagramOf(word2));

        string word3 = "cat";
        string word4 = "dog";

        Console.WriteLine(word3.IsAnagramOf(word4));
    }   

The output in this case would be

True

False

like image 30
Daniel Mann Avatar answered Oct 16 '22 23:10

Daniel Mann