0
尝试使用字典来实现此目的。目前,我有这样的方法:返回字符串中最常见的字符
/// <summary>
/// Returns the character(s) with the highest occurence in this string.
/// </summary>
/// <param name="str">the tring containing the characters</param>
/// <returns>the character or characters with the highest occurence</returns>
static char[] GetMostFrequentChar(string str)
{
var chars = new Dictionary<char, int>();
List<char> mostCommon = new List<char>();
for (int i = 0; i < str.Length; i++)
{
if (chars.ContainsKey(str[i]))
{
int curr = chars[str[i]];
chars[str[i]] = curr + 1;
} else // character not in dictionary
{
chars.Add(str[i], 1); // initial count for an added character is 1
}
}
foreach (KeyValuePair<char, int> entry in chars)
{
if (entry.Value == chars.Keys.Max())
{
mostCommon.Add(entry.Key);
}
}
char[] result = mostCommon.ToArray();
return result;
}
它应该返回一个包含最常见的字符(一个或多个)阵列,但我似乎每当我运行一个输入字符串这种方法来获得一个空数组。我哪里做错了?
我知道有些方法可以在没有字典的情况下做到,但我很好奇它如何与字典一起工作。
'如果(entry.Value == chars.Keys.Max())'我认为你的意思是'chars.Values.Max()' –
@KevinGosse我觉得超级愚蠢。非常感谢。这解决了它。 –