Anagrams-Two strings are said to be Anagrams of each other if they share the same set of letters to form the respective strings.
for example: Dog->god, seat->eats..
Input
Please Enter the First String
viswanath
Please Enter Second String
nathviswa
Output
Strings Viswanath and nathviswa are Anagrams
Algorithm:
step 1:
convert two strings into character arrays with Lower case or Upper case.
step 2:
sort the arrays in either ascending or descending order.
step 3:
convert the character arrays into strings
step 4:
compare the strings , if the are equal then strings are anagrams
else they are not anagrams.
C# program to print the given strings are anagrams or not.
Code:
class Anagram
{
static void Main(string[] args)
{ //Receive strings from User
Console.WriteLine("Please Enter the First String");
string firstString = Console.ReadLine();
Console.WriteLine("Please Enter Second String");
string secondString = Console.ReadLine();
//compare lengths of 2 strings
if(firstString.Length==secondString.Length)
{
//convert the strings into character arrays with lowercase
char[] ch1 = (firstString.ToLower()).ToCharArray();
char[] ch2 = (secondString.ToLower()).ToCharArray();
//sort the arrays
Array.Sort(ch1);
Array.Sort(ch2);
// convert the character arrays to strings
String word1 = new String(ch1);
string word2 = new String(ch2);
// if two words are equal then
if(word1==word2)
{
Console.WriteLine("Strings {0} and {1} are Anagrams ",firstString,secondString);
}
else
{
Console.WriteLine("Strings {0} and {1} are Not Anagrams ", firstString, secondString);
}
}
else
{//if 2 strings length are not equal
Console.WriteLine("Strings {0} and {1} are Not Anagrams ", firstString, secondString);
}
}
}
Output
Please Enter the First String
viswanath
Please Enter Second String
nathviswa
Strings viswanath and nathviswa are Anagrams