Pages

Tuesday, May 7, 2013

C#: Anagrams using Sort Method

Anagrams means strings having the same number of characters, but are rearranged.

//method for checking two strings are anagram
public void AnagramCheck(string str1,string str2)
{
//Remove if there are spaces in string
str1 = str1.Replace(" ","");
//Convert the string to Character Array
char[] firstStr1 = str1.ToCharArray();
str2 = str2.Replace(" ", "");
char[] secStr2 = str2.ToCharArray();

//Check whether two strings are equal length    
 if (str1.Length == str2.Length)
{
//strings with equal length
//Sort the character Array
Array.Sort(firstStr1);
Array.Sort(secStr2);


  //Loop through all elements in both character Array
  for(int i = 0; i < firstStr1.Length; i++)
  {
  //check all characters are equal in sorted char array
     if (firstStr1[i] == secStr2[i])
    {
     //Index reaches string length
    //all characters are equal
          if (i == firstStr1.Length-1)
         {
         Console.WriteLine("Anagrams");
         }
     //continue loop through all characters in the char array
     continue;
     }
    //when any character in char array not equals
   else
   {
   Console.WriteLine("Not Anagrams");
   break;
   }
  }
  }
//when two strings are not equal length
 else
 {
 Console.WriteLine("Not Anagrams");
 }
}


//Input Strings:
str1: twelve plus one
str2: eleven plus two
Output: Anagrams

str1: twelve plus one
str2: eleven pluy two
Output: Not Anagrams

3 comments: