Useful String Extension Method
By: Chris Missal
Page 1
Just in case you ever need this for an interview... Just kidding, this actually isn't very useful, at least not that I can imagine. At work we give a series of questions to potential developers. One of the questions is how you code a function to check if two strings are anagrams of one another. I always joke: "Just call the .IsAnagram() method.".
public static class StringExtensions
{
public static bool IsAnagram(this string str, string compareStr)
{
if (compareStr == null) return false;
char[] chrs = chrs = str.ToLower().Replace(" ", "").ToCharArray();
char[] compareChrs = compareStr.ToLower().Replace(" ", "").ToCharArray();
if (chrs.Length != compareChrs.Length) return false;
Array.Sort(chrs);
Array.Sort(compareChrs);
str = new String(chrs);
compareStr = new String(compareChrs);
return (str.Equals(compareStr));
}
}
The example on how to call the extension method:
///<summary>
///A test for IsAnagram
///</summary>
[TestMethod()]
public void IsAnagramTest()
{
string str = "The meaning of life";
string compareString = "The fine game of nil";
bool expected = true;
bool actual;
//actual = StringExtensions.IsAnagram(str, compareString);
actual = str.IsAnagram(compareString);
Assert.AreEqual(expected, actual);
}













