C# program to check if two Strings are anagrams of each other
Here's a C# program that checks if two strings are anagrams of each other:
using System;
class Program
{
static void Main()
{
string string1 = "listen";
string string2 = "silent";
bool areAnagrams = CheckAnagram(string1, string2);
if (areAnagrams)
{
Console.WriteLine("{0} and {1} are anagrams.", string1, string2);
}
else
{
Console.WriteLine("{0} and {1} are not anagrams.", string1, string2);
}
}
static bool CheckAnagram(string string1, string string2)
{
// Remove spaces and convert strings to lowercase
string1 = string1.Replace(" ", "").ToLower();
string2 = string2.Replace(" ", "").ToLower();
// Check if the lengths of the strings are equal
if (string1.Length != string2.Length)
{
return false;
}
// Create character frequency arrays
int[] charFrequency1 = new int[26];
int[] charFrequency2 = new int[26];
// Update character frequencies for string1
foreach (char c in string1)
{
charFrequency1[c - 'a']++;
}
// Update character frequencies for string2
foreach (char c in string2)
{
charFrequency2[c - 'a']++;
}
// Compare character frequencies
for (int i = 0; i < 26; i++)
{
if (charFrequency1[i] != charFrequency2[i])
{
return false;
}
}
return true;
}
}
In this program, we first remove any spaces and convert both strings to lowercase using the 'Replace' and 'ToLower' methods, respectively. Then, we check if the lengths of the strings are equal. If they are not, we return 'false' because anagrams must have the same number of characters.
Next, we create two integer arrays, 'charFrequency1' and 'charFrequency2', of size 26 to represent the frequency of each lowercase character from 'a' to 'z'. We iterate over each character in the first string and update its frequency in 'charFrequency1', and similarly for the second string and 'charFrequency2'.
Finally, we compare the character frequencies in both arrays. If any frequency differs, we return 'false'. If all frequencies are the same, we return 'true', indicating that the strings are anagrams.
In the example above, the output would be:
listen and silent are anagrams.
Both "listen" and "silent" have the same characters, and thus they are anagrams of each other.