This program shows how you can check if two given input strings are
Anagrams or not in CSharp language. Anagrams are two different words or combinations of characters which have the same
alphabets and their counts. Therefore a particular set of alphabets can
create many permutations of Anagrams. In other words, if we have the
same set of characters in two words(strings) then they are Anagrams.
We
create a function that has input as a character array pair of inputs. When we get the two different sets of characters, we check the count of each alphabet in these two sets. Finally, we tally and check if the value of character count for each alphabet is the same or not in these sets. If all characters occur at the same rate in both the sets of characters, then we declare the sets to be Anagrams otherwise not.
See the code below for C#:
using System;
namespace Anagram_Test
{
class ClassCheckAnagram
{
public int check_anagram(char[] a, char[] b)
{
Int16[] first = new Int16[26];
Int16[] second = new Int16[26];
int c = 0;
for (c = 0; c < a.Length; c++)
{
first[a[c] - 'a']++;
}
c = 0;
for (c=0; c<b.Length; c++)
{
second[b[c] - 'a']++;
}
for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}
return 1;
}
}
}
using System;
namespace Anagram_Test
{
class Program
{
static void Main(string[] args)
{
ClassCheckAnagram cca = new ClassCheckAnagram();
Console.WriteLine("Enter first
string\n");
string aa = Console.ReadLine();
char[] a = aa.ToCharArray();
Console.WriteLine("\nEnter
second string\n");
string bb = Console.ReadLine();
char[] b = bb.ToCharArray();
int flag = cca.check_anagram(a, b);
if (flag == 1)
Console.WriteLine("\nThey are
anagrams.\n");
else
Console.WriteLine("\nThey are
not anagrams.\n");
Console.ReadKey();
}
}
}