返回字符串

时间:2016-11-25 07:06:12

标签: c# dictionary

尝试使用Dictionary实现此目的。目前,我有这种方法:

/// <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; 
}

它应该返回一个包含最频繁字符的数组,但每当我在输入字符串上运行此方法时,我似乎得到一个空数组。我哪里做错了?

我知道有很多方法可以在没有字典的情况下完成,但我很好奇它是如何使用字典的。

2 个答案:

答案 0 :(得分:2)

嗯,这是一个Linq - 方法Dictionary

static char[] GetMostFrequentChar(string str)
{
    Dictionary<char, int> result = str.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
    return result.Where(x => x.Value == result.Values.Max()).Select(x => x.Key).ToArray();
}

答案 1 :(得分:1)

Kevin Gosse已经给你答案,但你可以简化你的代码:

private static char[] GetMostFrequentChar(string str)
{
    Dictionary<char, int> chars = new Dictionary<char, int>();

    foreach (char c in str)
    {
        if (chars.ContainsKey(c)) chars[c]++;
        else chars.Add(c, 1);
    }

    int max = chars.Values.Max();
    return chars.Where(b => b.Value == max).Select(b => b.Key).ToArray();
}