As @Pimgd pointed out, it is also incorrect. So how can we fix it? Two strings are anagrams if each character occurs the same number of times, so that seems like a likely approach.
Let's write a method to count the occurrences of each character in a string. We'll use a Dictionary<char, int>
to keep track.
private static IDictionary<char, int> GetCharacterCount(string input)
{
var tally = new Dictionary<char, int>();
foreach (var c in input)
{
int count = tally.TryGetValue(c, out count)
? count + 1
: 1;
tally[c] = count;
}
return tally;
}
Now we want to compare the results of this method
var s1Count = GetCharacterCount(s1);
var s2Count = GetCharacterCount(s2);
foreach (var c in s1)
{
if (!s2Count.ContainsKey(c))
{
return false;
}
if (s1Count[c] != s2Count[c])
{
return false;
}
}
return true;
Well, that's one approach, but it seems a bit complicated.
Anagrams have another useful properly, which is that two strings are anagrams of each other if and only if they are equal when they are sorted. So let's convert that into code.
To sort a string, we first have to convert it into a character array, sort the array, and then convert back into a string.
private static string Sort(string input)
{
var chars = input.ToCharArray();
Array.Sort(chars);
return new string(chars);
}
Now we can compare the two sorted arrays
var s1Sorted = Sort(s1);
var s2Sorted = Sort(s2);
for (var i = 0; i < s1Sorted.Length; i++)
{
if (s1Sorted[i] != s2Sorted[i])
{
return false;
}
}
return true;